 # 1431. Kids With the Greatest Number of Candies

Updated: 2023-09-01 LeetCode problem

## Problem Statement

The problem requires us to find out which kids can potentially have the greatest number of candies if they are given all the extra candies. The information about the number of candies each kid has and the number of extra candies available is given.

## Naive Solution

A naive approach to this problem would be to iterate over the candies array for each kid and check if adding the extra candies to the kid’s current candies makes it equal to or greater than the maximum candies any kid has. This approach would have a time complexity of O(n^2) due to the nested loops.

## Efficient Solution

A more efficient approach would involve two steps:

1. Find the maximum number of candies any kid has. This can be done using Python’s max function.
2. Iterate over the candies array and check if adding the extra candies to the current candies of a kid makes it equal to or greater than the maximum candies. If so, add True to the result list, otherwise add False.

This approach has a time complexity of O(n) which is an improvement over the naive solution.

## Steps

Here are the high-level steps of the algorithm:

1. Find the maximum number of candies any kid has.
2. Iterate over the candies array and add True to the result list if a kid can have the greatest number of candies after receiving all the extra candies, otherwise add False.

## Python Solution

Here is a Python solution that implements the above algorithm:

class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
max_candies = max(candies)
return [candy + extraCandies >= max_candies for candy in candies]


In the kidsWithCandies method, we first find the maximum number of candies any kid has. We then use list comprehension to create the result list.

This problem shows how a problem that seems to require nested loops can be solved efficiently with a single pass over the array by making use of Python’s built-in functions and list comprehension. It’s a good practice problem for beginners to understand the concepts of array manipulation and using built-in functions.