leetcode 之Candy(12)
这题的思路很巧妙,分两遍扫描,将元素分别和左右元素相比较。
int candy(vector<int> &rattings) { int n = rattings.size(); vector<int> incrment(n); int inc = 1; //和左边比较 for (int i = 1; i < n; i++) { if (rattings[i]>rattings[i - 1]) incrment[i] = max(inc++, incrment[i]); else inc = 1; } inc = 1; //和右边比较(把漏掉的第一个补上) for (int i = n - 2; i >= 0; i--) { if (rattings[i] > rattings[i + 1]) incrment[i] = max(inc++, incrment[i]); else inc = 1; } //每人至少一个(将incrment的元素相加,再加上n) return accumulate(&incrment[0], &incrment[0] + n, n); }