Candy LeetCode solution in Java

1
class Solution {
2
public int candy(int[] ratings) {
3

4
int[] left = new int[ratings.length];
5
Arrays.fill(left, 1);
6

7
// we are checking from left to right that if the element next to our current element has
8
// greater rating, if yes then we are increasing their candy
9
for (int i = 0; i < ratings.length - 1; i++) {
10
if (ratings[i] < ratings[i + 1]) left[i + 1] = left[i] + 1;
11
}
12

13
int[] right = new int[ratings.length];
14
Arrays.fill(right, 1);
15

16
// we are checking from right to left if the element after than our current element is greater
17
// or not , if yes then we are also checking their candies if greater rating has less number of
18
// candies then increasing their candy
19
for (int i = ratings.length - 2; i >= 0; i--) {
20
if (ratings[i + 1] < ratings[i] && right[i] <= right[i + 1]) right[i] = right[i + 1] + 1;
21
}
22
int sum = 0;
23
for (int i = 0; i < right.length; i++) {
24
sum += Math.max(right[i], left[i]);
25
}
26

27
return sum;
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0