[LeetCode] Kids With the Greatest Number of Candies

코테연습|2024. 9. 16. 15:53

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/description/?envType=study-plan-v2&envId=leetcode-75

 

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note 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: If you give all extraCandies to:

- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.

- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.

- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.

- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.

- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest 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.

Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.

Example 3:

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

Output: [true,false,true]

 

Constraints:

  • n == candies.length
  • 2 <= n <= 100
  • 1 <= candies[i] <= 100
  • 1 <= extraCandies <= 50

 

아이들이 가진 사탕의 수로 이루어진 int[] 가 있고, 추가로 한 명의 아이에게 줄 사탕의 수 int가 있다.

아이들 중 한 명에게 사탕을 주었을 때, 이 아이가 사탕을 가장 많이 가진 아이가 되는지 여부를 boolean[] 으로 리턴하는 문제.

 

function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
    const result = []
    for(let i=0; i<candies.length; i++){
        candies[i] = candies[i] + extraCandies;
        result.push(Math.max(...candies) === candies[i])
        candies[i] = candies[i] - extraCandies;
    }

    return result;
};

 

단순히 반복문 내에서 추가 사탕의 수를 더해주고,

더해진 사탕 수가 반영된 배열 내에서 최대 값을 비교한 뒤 다시 배열 내 값을 원상복구시켰다.

 

function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
  const max = Math.max(...candies);
  return candies.map((candyNum) => candyNum + extraCandies >= max);
};

 

근데 불필요하게 더하고 빼고 할 것 없이,

[추가로 사탕을 받기 전 최대의 사탕 수]와 [사탕이 더해졌을 때 사탕 수] 를 비교하면 사탕을 받은 아이가 MAX인지 판단할 수 있다.

'코테연습' 카테고리의 다른 글

[LeetCode] Can Place Flowers  (0) 2024.09.16
[LeetCode] Greatest Common Divisor of Strings  (0) 2024.09.15
[LeetCode] Merge Strings Alternately  (0) 2024.06.27