forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCandy.java
More file actions
31 lines (26 loc) · 832 Bytes
/
Candy.java
File metadata and controls
31 lines (26 loc) · 832 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int candy(int[] ratings) {
if (ratings.length <= 1) {
return ratings.length;
}
int[] candies = new int[ratings.length];
for (int i = 0; i < ratings.length; i++) {
candies[i] = 1;
}
for (int i = 1; i < ratings.length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (int i = ratings.length - 1; i > 0; i--) {
if (ratings[i - 1] > ratings[i]) {
candies[i - 1] = Math.max(candies[i] + 1, candies[i - 1]);
}
}
int candyCount = 0;
for (int candy : candies) {
candyCount += candy;
}
return candyCount;
}
}