Loading

LeetCode problem#1431

Kids With the Greatest Number of Candies

Solved in 2 languagesJavaC#

Solve it on LeetCode(opens in a new tab)

Solution

22 lines
1class Solution {
2    // time O(n)
3    // space O(n)
4    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
5        List<Boolean> result = new ArrayList<Boolean>(candies.length);
6
7        // First the greatest number of candies a kid has
8        int greatest = candies[0];
9        for (int i = 1; i < candies.length; i++) {
10            if (candies[i] > greatest) {
11                greatest = candies[i];
12            }
13        }
14
15        for (int i = 0; i < candies.length; i++) {
16            boolean hasGreatest = candies[i] + extraCandies >= greatest;
17            result.add(hasGreatest);
18        }
19
20        return result;
21    }
22}
1public class Solution {
2    public IList<bool> KidsWithCandies(int[] candies, int extraCandies) {
3        int greatest = 0;
4        IList<bool> result = new List<bool>(candies.Length);
5        
6        foreach (int candyCount in candies) {
7            if (candyCount > greatest) {
8                greatest = candyCount;
9            }
10        }
11
12        foreach (int candyCount in candies) {
13            result.Add(candyCount + extraCandies >= greatest);
14        }
15
16        return result;
17    }
18}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.