题解 | #分糖果问题# [S-P0]
分糖果问题
http://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
[S-P2] 贪心
先满足从左向右,再满足从右向左
从右向左时,如果i糖比i-1糖多 => i分比i-1分高,i-1这波一定不需要再多拿糖。
所以i只需要满足和i+1之间的关系就行
import java.util.*;
public class Solution {
public int candy (int[] arr) {
int[] candies = new int[arr.length];
Arrays.fill(candies, 1);
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i-1])
candies[i] = candies[i-1] + 1;
}
for (int i = arr.length-2; i >= 0; i--) {
if (arr[i] > arr[i+1]) {
if (candies[i] > candies[i+1]) continue; // already has more candies
else candies[i] = candies[i+1]+1;
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
}