Kids With the Greatest Number of Candies LeetCode solution in Java

1
class Solution {
2
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
3
List<Boolean> result =
4
new ArrayList<>(candies.length); // better practice since the length is known
5
int theHighest =
6
candies[
7
0]; // always good practice to start from known value or to check constraints, 0 or -1
8
for (int i = 1; i < candies.length; i++) {
9
theHighest =
10
Math.max(theHighest, candies[i]); // returns the greatest value for us to compare later
11
}
12
// Since we are comparing with greatest value, we can use math logic to subtract extraCandies
13
// the other side
14
// (candies[i]+extraCandies >= theHighest) or (candies[i] >= theHighest-extraCandies)
15
int mathLogic = theHighest - extraCandies;
16
for (int i = 0; i < candies.length; i++) {
17
// logic: 6+5>=10 or 6 >=10-5
18
if (candies[i] >= mathLogic) {
19
result.add(true);
20
} else {
21
result.add(false);
22
}
23
}
24
return result;
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0