Kids With the Greatest Number of Candies

Given the array candies and the integer extra candles, where candies[i] represents the number of candies that the ith kid has.
Check if there is a way to distribute extra candies among the kids such that he or she can have the greatest number of candies among them.

Example 1:

Input: candies[] = {2,3,5,1,3}, extraCandies = 3
Output: [true,true,true,false,true] 

Approach:

Java

import java.util.ArrayList;
import java.util.List;

public class KidsWithCandies {
    public static void main(String[] args) {
        int candies[] = { 23513 };
        int extraCandies = 3;
        List<Booleanl = kidsWithCandies(candies, extraCandies);
        System.out.println(l.toString());
    }

    public static List<BooleankidsWithCandies(int[] candiesint extraCandies) {
        List<Booleanlist = new ArrayList<>();
        int maxElm = maxElement(candies);
        for (int i : candies) {
            if (maxElm <= extraCandies + i) {
                list.add(true);
            } else {
                list.add(false);
            }
        }
        return list;

    }

    // find maximum element
    private static int maxElement(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max)
                max = arr[i];
        }
        return max;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

vector<boolkidsWithCandies(vector<int>& candies
      int extraCandies
{
        vector<boolres;
        int max1=INT_MIN;
        int n=candies.size();
        for(int i=0;i<n;i++)
              if(candies[i]>max1)
                    max1=candies[i];
       for(int i=0;i<n;i++)
        {
          if(candies[i]==max1
                res.push_back(true);
          else if(candies[i]+extraCandies>=max1)
                 res.push_back(true);
          else
              res.push_back(false);
        }
        return res;
}
int main()
{
 vector<intcandies ={2,3,5,1,3};
 int extraCandies = 3;
 vector<boolextrakidsWithCandies(candies,extraCandies);
 for(int i=0;i<extra.size();i++)
    cout<<extra[i]<<" ";
 return 0;
}




No comments:

Post a Comment