forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
135_candy.java
33 lines (31 loc) · 901 Bytes
/
135_candy.java
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
32
33
//time:O(n)
//initial全为1
//从左到右扫一遍,更新所有candy值,
//从右往左扫一遍,更新所有candy值。n
public class Solution {
public int candy(int[] ratings) {
if(ratings == null || ratings.length ==0) return 0;
int len = ratings.length;
int[] candy = new int[len];
Arrays.fill(candy, 1);
for(int i = 0; i < len-1; i++){
if(ratings[i] < ratings[i+1]){
candy[i+1] = Math.max(candy[i+1], candy[i]+1);
} else{
continue;
}
}
for(int i = len-1; i> 0; i--){
if(ratings[i-1] > ratings[i]){
candy[i-1] = Math.max(candy[i-1], candy[i]+1);
} else{
continue;
}
}
int sum = 0;
for(int n: candy){
sum+=n;
}
return sum;
}
}