본문 바로가기

공부, 알고리즘/LeetCode (리트코드)

[리트코드/JAVA] 1431. Kids With the Greatest Number of Candies

leetcode.com/problems/kids-with-the-greatest-number-of-candies/

 

Kids With the Greatest Number of Candies - 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

 

# 문제설명

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.

 

배열 candies에는 어린이가 각각 가지고 있는 사탕의 개수가 들어있습니다.

어린이에게 extraCandies를 추가로 주었을 때 전체 어린이 중 가장 많은 사탕을 갖게 되면 true, 그렇지 않으면 false를 리턴하는 배열을 만드세요. 단, 가장 많은 사탕의 수와 동점이어도 true를 반환하세요.

 

# 제한사항

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

# 입출력 예

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.

 

# 풀이

import java.util.*;

class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {   
        ArrayList<Boolean> list = new ArrayList<>();
        
        int maxKid = 0;
        for(int i : candies) 
            maxKid = Math.max(maxKid, i);
            
        for(int candy : candies) {
            int tmp = candy + extraCandies;
            
            if(tmp >= maxKid) list.add(true);
            else list.add(false);
        }
        
        return list;
    }
}

 

 

#5, 7

리턴할 list를 선언하고 candies배열에서 가장 큰 수를 담을 int 변수 maxKid를 선언한다.

 

#8 ~ 9

for문을 활용해서 candies배열 중에서 가장 큰 숫자를 찾아서 maxKid에 담는다.

 

#12

candies배열의 값과 extraCandies의 수를 더해서 tmp에 넣는다.

 

#14 ~ 15

만약 tmp의 숫자가 maxKid의 숫자보다 크거나 같으면 list에 true를 추가하고 그렇지않으면 false를 추가한다.

 

#18

true와 false가 들어간 list를 리턴하고 함수를 종료한다.