본문 바로가기

알고리즘 풀이(JAVA)/leetcode

[leetcode] 1431. Kids With the Greatest Number of Candies (java)

<문제 1431. Kids With the Greatest Number of Candies >

[문제]

번역 :

[사탕을 가진 아이가 n명 있습니다. candies[i]는 아이가 가진 사탕의 개수를 나타내는 정수 배열 candies이며,

여분의 사탕의 개수를 의미하는 정수 extraCandies가 주어집니다.

결과는 길이 n의 부울 배열을 반환하며, 여기서 result[i]는 i번째 아이에게 각각 extraCandies를 준 후 모든 아이 중에서 가장 많은 수의 사탕을 갖게 되면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

여러 어린이가 가장 많은 사탕을 가질 수 있다는 점에 주의 하여야 합니다.]

 

→ extraCandies를 주는 시점에서, i번째 아이가 '모든 아이 중에서 가장 많은 수의 사탕을 가지고 있으면'  

True를 반환하고, 그게 아니라면 false를 반환하면 되는 문제

주의할 점은, '같거나 크면 true' 라는 부분이다.(= 여러 어린이가 가장 많은 사탕을 가질 수 있다)

 

[답안]

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        int max = 0; // 처음 최댓값을 구할 max 변수
        List<Boolean> answer = new ArrayList<>(); // 결과값을 저장할 answer(boolean타입)

        for (int i = 0; i < candies.length; i++) { // 처음 최댓값을 구하기 위한 for문
            if (candies[i] > max) {
                max = candies[i];
            }
        }

        for (int i = 0; i < candies.length; i++) { 
            if (candies[i] + extraCandies >= max) { // 해당 인덱스 + 여분의 캔디 값이 최댓값보다 크거나 같으면
                answer.add(true); // true를 저장(answer에)
            } else { // 아니라면
                answer.add(false); // false를 저장(answer에)
            }
        }
        return answer; // answer return
    }

    public static void main(String args[]) {
        Solution sol = new Solution();
        int[] candies = {2,3,5,1,3};
        int extraCandies = 3;
        System.out.println(sol.kidsWithCandies(candies, extraCandies));
    }
}

출처

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

 

Kids With the Greatest Number of Candies - LeetCode

Can you solve this real interview question? Kids With the Greatest Number of Candies - 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 extraCandie

leetcode.com