프로그래밍/Online Judge

LeetCode) 1431.Kids With the Greatest Number of Candies 풀이 (with.JavaScript)

삐제제 2021. 5. 12. 17:18

난이도 : Easy

문제 :

Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.

For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.

 

테스트 케이스 :

Example 1:Input: candies = [2,3,5,1,3], extraCandies = 3

Output: [true,true,true,false,true]

Explanation: Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. Kid 3 has 5 candies and this is already the greatest number of candies among the kids. Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.

Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1

Output: [true,false,false,false,false]

Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy.

Example 3:

Input: candies = [12,1,12], extraCandies = 10

Output: [true,false,true]

 

 

문제 설명 : 

extraCandies를 더했을때, 최댓값(크거나 같은)이면 boolean 타입 배열에 true, 아니면 false를 넣어주고 그 배열을 반환하는 문제입니다.

Math객체를 이용해서 쉽게 풀었던것 같습니다.

 

/**
 * @param {number[]} candies
 * @param {number} extraCandies
 * @return {boolean[]}
 */
var kidsWithCandies = function(candies, extraCandies) {
    var result = [];
    for(i = 0; i < candies.length; i++){
        var isGreatest = candies[i] + extraCandies;
        if(isGreatest >= Math.max.apply(null, candies)){
            result[i] = true;
        } else {
            result[i] = false;
        }    
    }
    return result;
};

1. boolean 타입 변수를 담을 빈 배열 result 선언, 후에 for문을 이용하여 순서대로 비교

2. isGreatest 변수는 배열에 들어있는 숫자에 extraCandies를 더해준 값입니다.

3. isGreatest 변수가 candies 배열의 최댓값과 비교했을때 크거나 같으면

4. true값을 result 배열에 넣어줍니다.

5. 이외의 값은 false를 result 배열에 넣어줍니다.

 

Math.max.apply() 메소드를 이용하여 쉽게 해결한 문제입니다.

참고문서 : 

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/max

 

Math.max() - JavaScript | MDN

Math.max()함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.

developer.mozilla.org

요즘 천천히 공부하면서 알고리즘 문제를 풀어보고있는데

 

내장객체만을 이용해서 문제를 해결하는 연습도 많이 해야할것같습니다 ㅠㅠ