题解 | #分糖果问题#
分糖果问题
http://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
O(n), O(1), slope算法。重点:
if down >= peak: res += 1
这一部分考虑了下降超过上升数的情况
# # pick candy # @param arr int整型一维数组 the array # @return int整型 # class Solution: def candy(self , arr ): # write code here n = len(arr) up, down = 0, 0 res, peak = 1, 1 print(0, up, down, peak, res) for i in range(1, n): if arr[i] > arr[i-1]: down=0 up += 1 res += up+1 peak = up+1 elif arr[i] < arr[i-1]: up=0 down += 1 res += down if down >= peak: res += 1 else: res += 1 peak = 1 up, down = 0, 0 print(i, up, down, peak, res) return res