알고리즘, 자료구조/Hackerrank

Hacker Rank JavaScript: Birthday Cake Candles

soohkang 2021. 5. 18. 14:06
728x90

출처:

https://www.hackerrank.com/challenges/birthday-cake-candles/problem

 

Birthday Cake Candles | HackerRank

Determine the number of candles that are blown out.

www.hackerrank.com

 

조건에 맞게 함수를 완성하시오.

 

테스트에 모두 통과하지 못했던 방식

내가 맨 처음에 작성한 방법

function birthdayCakeCandles(candles) {
    // Write your code here
    let n = candles.length;
    let max = Number.MIN_SAFE_INTEGER;
    let cnt = 0;
    
    for(let i = 0; i < n; i++) {
        if(candles[i] >= max) {
            max = candles[i];
            cnt++;
        }
    }
    
    return cnt;
}

 

 

테스트에 모두 통과한 코드

구글에 birthday cake candles javascript라고 검색해서 몇 개의 블로그를 통해 확인한 방법

function birthdayCakeCandles(candles) {
    // Write your code here
    let n = candles.length;
    let max = Number.MIN_SAFE_INTEGER;
    let cnt = 0;
    
    for(let i = 0; i < n; i++) {
        if(candles[i] > max) {
            max = candles[i];
            cnt = 1;
        }
        else if (candles[i] === max) {
            cnt++;
        }
    }
    
    return cnt;
}