<AI/>
enru
Все статьи

Kids with the greatest number of candies

LeetCode 1431: Check for each kid whether giving them all the extra candies makes their count the greatest.

Сложность
Легкая
Опубликовано
Темы
#array
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

There are n kids with candies.

You are given an integer array candies, where candies[i] is the number of candies the i-th kid has, and an integer extraCandies, the number of extra candies you have.

Return an array result of length n, where result[i] is true if, after giving the i-th kid all the extra candies, they will have the greatest number of candies among all kids, or false otherwise.

Note that multiple kids can have the greatest number of candies at the same time.

Constraints

  • The length of candies is in the range from 1 to 100
  • Each kid has at least 1 and at most 100 candies
  • extraCandies is in the range from 1 to 50

Examples

Input: candies = [2,3,5,1,3], extraCandies = 3

Answer: [true,true,true,false,true]

Solution

We can find the maximum number of candies among all kids and then check whether a particular kid's count reaches that maximum after adding extraCandies to it.

typescript
export const kidsWithCandies = (candies: number[], extraCandies: number): boolean[] => {
  let res: boolean[] = [];
 
  const maxCandies = Math.max(...candies);
 
  candies.forEach((count) => {
    res.push(count + extraCandies >= maxCandies);
  });
 
  return res;
};

Complexity Analysis

Time Complexity

To find the answer we iterate over the array twice, i.e. perform 2n operations. The overall time complexity is O(n).

Space Complexity

The space complexity is linear: O(n), since we create an array of length n to store the answer.