Similar Problems

Similar Problems not available

Kids With The Greatest Number Of Candies - Leetcode Solution

Companies:

  • adobe
  • amazon

LeetCode:  Kids With The Greatest Number Of Candies Leetcode Solution

Difficulty: Easy

Topics: array  

Problem Statement:

We are given an integer array candies, where each element represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

We need to return a boolean array result of size n, where result[i] is true if after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids. Otherwise, result[i] is false.

Example: Input: candies = [2,3,5,1,3], extraCandies = 3 Output: [true,true,true,false,true] Explanation: Kid 0 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. Kid 1 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. Kid 2 has 5 candies and this is already the greatest number of candies among the kids. Kid 3 has 1 candy and even if he or she receives all extra candies will only have 4 candies. Kid 4 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids.

Solution:

To solve this problem, we first need to find the maximum number of candies among all the kids. After that, we will iterate through each kid and check whether after giving extraCandies to that kid, they have the maximum number of candies or not. We will use a boolean array to store whether each kid has the maximum number of candies or not.

Algorithm:

  1. Initialize an empty boolean array result of size n.
  2. Find the maximum number of candies among all the kids using max() function.
  3. For each kid i, check if the number of candies after adding extraCandies is greater or equal to the maximum number of candies.
  4. If yes, then Set result[i] to true. Else, set it to false.
  5. Return result.

Code in Python:

class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        n = len(candies)
        result = [False]*n
        maxCandies = max(candies)
        for i in range(n):
            if candies[i] + extraCandies >= maxCandies:
                result[i] = True
        return result

Time Complexity: O(n) - As we are iterating over the array only once. Space Complexity: O(n) - We are using a boolean array of size n to store the result.

Kids With The Greatest Number Of Candies Solution Code

1