Open songyy5517 opened 6 months ago
Approach: Travarase the array
Complexity Analysis
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
// Intuition: Looks simple, a strightforward idea is to first find the maximum
// number in the array, and then travarse the array and compare each element + extra
// with the maximum value.
// 1. Exception handling
if (candies == null || candies.length == 0)
return new ArrayList();
// 2. Find the maximum number
int max = candies[0];
for (int i = 0; i < candies.length; i++)
max = candies[i] > max ? candies[i] : max;
// 3. Compare each element + extra with the maximum
ArrayList<Boolean> res = new ArrayList();
for (int i = 0; i < candies.length; i++){
res.add(candies[i] + extraCandies >= max);
}
return res;
}
}
2024/5/8
There are
n
kids with candies. You are given an integer arraycandies
, where eachcandies[i]
represents the number of candies theith
kid has, and an integerextraCandies
, denoting the number of extra candies that you have.Return a boolean array result of length 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, or false otherwise.Note that multiple kids can have the greatest number of candies.
Example 1:
Example 2:
Example 3:
Intuition This problem mainly examines the operations of array. A simple idea is to first find the maximum in the array, and then compare each element plus extraCandies with the maximum, then store the result in a Boolean ArrayList and finally return.