题解 | #分糖果问题#
分糖果问题
http://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
import java.util.*;
public class Solution {
/**
* pick candy
* @param arr int整型一维数组 the array
* @return int整型
*/
public int candy (int[] arr) {
// write code here
int N = arr.length;
int ans = 1;
int inc = 1, dec = 0, pre = 1;
for (int i = 1; i < N; i++) {
if (arr[i] >= arr[i - 1]) {
dec = 0;
pre = arr[i] == arr[i - 1] ? 1 : pre + 1;
ans += pre;
inc = pre;
} else {
dec++;
if (dec == inc) {
dec++;
}
ans += dec;
pre = 1;
}
}
return ans;
}
}