funccandy(ratings []int) (ans int) { n := len(ratings) left := make([]int, n) for i, r := range ratings { if i > 0 && r > ratings[i-1] { left[i] = left[i-1] + 1 } else { left[i] = 1 } } right := 0 for i := n - 1; i >= 0; i-- { if i < n-1 && ratings[i] > ratings[i+1] { right++ } else { right = 1 } ans += max(left[i], right) } return }
funcmax(a, b int)int { if a > b { return a } return b }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defcandy(self, ratings: List[int]) -> int: n = len(ratings) left = [0] * n for i inrange(n): if i > 0and ratings[i] > ratings[i - 1]: left[i] = left[i - 1] + 1 else: left[i] = 1 right = ret = 0 for i inrange(n - 1, -1, -1): if i < n - 1and ratings[i] > ratings[i + 1]: right += 1 else: right = 1 ret += max(left[i], right) return ret
var candy = function(ratings) { const n = ratings.length; const left = newArray(n).fill(0); for (let i = 0; i < n; i++) { if (i > 0 && ratings[i] > ratings[i - 1]) { left[i] = left[i - 1] + 1; } else { left[i] = 1; } }
let right = 0, ret = 0; for (let i = n - 1; i > -1; i--) { if (i < n - 1 && ratings[i] > ratings[i + 1]) { right++; } else { right = 1; } ret += Math.max(left[i], right); } return ret; };
classSolution { public: intcandy(vector<int>& ratings){ int n = ratings.size(); int ret = 1; int inc = 1, dec = 0, pre = 1; for (int i = 1; i < n; i++) { if (ratings[i] >= ratings[i - 1]) { dec = 0; pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1; ret += pre; inc = pre; } else { dec++; if (dec == inc) { dec++; } ret += dec; pre = 1; } } return ret; } };
funccandy(ratings []int)int { n := len(ratings) ans, inc, dec, pre := 1, 1, 0, 1 for i := 1; i < n; i++ { if ratings[i] >= ratings[i-1] { dec = 0 if ratings[i] == ratings[i-1] { pre = 1 } else { pre++ } ans += pre inc = pre } else { dec++ if dec == inc { dec++ } ans += dec pre = 1 } } return ans }
classSolution: defcandy(self, ratings: List[int]) -> int: n = len(ratings) ret = 1 inc, dec, pre = 1, 0, 1
for i inrange(1, n): if ratings[i] >= ratings[i - 1]: dec = 0 pre = (1if ratings[i] == ratings[i - 1] else pre + 1) ret += pre inc = pre else: dec += 1 if dec == inc: dec += 1 ret += dec pre = 1 return ret
intcandy(int* ratings, int ratingsSize) { int ret = 1; int inc = 1, dec = 0, pre = 1; for (int i = 1; i < ratingsSize; i++) { if (ratings[i] >= ratings[i - 1]) { dec = 0; pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1; ret += pre; inc = pre; } else { dec++; if (dec == inc) { dec++; } ret += dec; pre = 1; } } return ret; }