N

(Leet Code JS)Candy 본문

Leet Code 알고리즘

(Leet Code JS)Candy

naeunchan 2022. 7. 10. 15:43
728x90
반응형

https://leetcode.com/problems/candy/

 

Candy - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

var candy = function(ratings) {
    const { length } = ratings;
    const fromLeft = Array.from({length}, () => 1);
    const fromRight = Array.from({length}, () => 1);
    let answer = 0;
    
    for(let i = 1; i < length; i++){
        const current = ratings[i];
        const before = ratings[i - 1];
        
        if(current > before){
            fromLeft[i] = fromLeft[i - 1] + 1;
        }
    }
    
    for(let i = length - 2; i >= 0; i--){
        const current = ratings[i];
        const next = ratings[i + 1];
        
        if(current > next){
            fromRight[i] = fromRight[i + 1] + 1;
        }
    }
    
    for(let i = 0; i < length; i++){
        answer += Math.max(fromLeft[i], fromRight[i]);
    }
    
    return answer;
};
728x90
반응형