#1431

Kids With the Greatest Number of Candies

Easy
ArrayArrayMax/Min Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of finding the maximum for each kid, we can find the maximum once and then use it to check each kid's total candies. This reduces the number of times we search for the maximum, making it much faster.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the maximum number of candies any kid currently has.
  2. 2Step 2: Create a result array initialized to false.
  3. 3Step 3: For each kid, check if their candies plus extraCandies is greater than or equal to the maximum candies. If true, set the corresponding index in the result array to true.
solution.py3 lines
1def kidsWithCandies(candies, extraCandies):
2    max_candies = max(candies)
3    return [c + extraCandies >= max_candies for c in candies]

Complexity note: The time complexity is O(n) because we find the maximum once (O(n)) and then check each kid (O(n)). This is efficient for larger inputs.

  • 1Finding the maximum number of candies only once significantly reduces the time complexity.
  • 2Understanding the problem allows for a more efficient solution rather than brute-forcing through each possibility.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.