Kids With the Greatest Number of Candies — Easy Problem & Solution

candies[i] is how many sweets kid i has, and you hold extraCandies more.

  • Difficulty: Easy
  • Topics: Arrays
  • Asked at: Amazon, Google, Infosys
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

candies[i] is how many sweets kid i has, and you hold extraCandies more.

For each kid, answer 1 if giving them all the extra sweets would leave them with the greatest number among all the kids — possibly tied — and 0 otherwise.

Example 1

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [1,1,1,0,1]
Explanation: Only the kid with 1 sweet still falls short of 5.

Example 2

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [1,0,0,0,0]
Explanation: The extra sweet is not enough for anyone else to catch up to 4.

Example 3

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

Constraints

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

How to solve Kids With the Greatest Number of Candies

Take the maximum once, then each kid's answer is candies[i] + extraCandies >= max.

Approach

  1. Scan for the largest value.
  2. For each kid, compare their total with that maximum.

Why it works

The extra sweets are handed to one kid at a time in each hypothetical, so the other kids' counts — and therefore the maximum — never move. That is what lets the maximum be computed once up front rather than per kid, turning an O(n²) check into O(n).

Complexity

  • Time — O(n)
  • Space — O(n) for the output

Pitfalls

  • Recomputing the maximum per kid is needless work.
  • The comparison is >=: tying with the greatest still counts.
  • The extra sweets are not shared; each kid is considered as if given all of them.

Reference solution

Python

from typing import List

def kidsWithCandies(candies: List[int], extraCandies: int) -> List[int]:
    mx = max(candies)
    return [1 if c + extraCandies >= mx else 0 for c in candies]

JavaScript

var kidsWithCandies = function(candies, extraCandies) {
    var mx = 0, i;
    for (i = 0; i < candies.length; i++) if (candies[i] > mx) mx = candies[i];
    var out = [];
    for (i = 0; i < candies.length; i++) out.push(candies[i] + extraCandies >= mx ? 1 : 0);
    return out;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue