[알고리즘] LeetCode_#1431

Yuri·2024년 12월 16일

코딩테스트

목록 보기
3/9

1431. 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 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

🚨 Constraints

▶︎ 풀이

n번째 아이가 extraCandies를 받았을 때, 가장 많은 candies를 가지고 있으면 true, 아니면 false.
candies[i] 중 가장 큰 수가 greatestCandies 일 때, n번째 인덱스의 수와 extraCandies이 greatestCandies 보다 크거나 같으면 n번째 아이는 가장 많은 캔디를 가진다.

  1. 반복문을 통해 비교하며 greatestCandies를 찾는다.
  2. 반복문에서 cadies[i] + extraCandies >= greatestCandies 를 하여 true, false를 결과(result) 배열에 담는다.

▶︎ 소스코드

class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        List<Boolean> result = new ArrayList<>();
        int greatestCandies = 0;
        for (int j : candies) {
            if (j > greatestCandies) {
                greatestCandies = j;
            }
        }
        for (int candy : candies) {
            if(candy + extraCandies >= greatestCandies) {
                result.add(true);
            } else {
                result.add(false);
            }
        }
        return result;
    }
}
profile
안녕하세요 :)

0개의 댓글