135. 分发糖果
135. 分发糖果
https://leetcode.cn/problems/candy/description/?envType=study-plan-v2&envId=top-interview-150
Code
class Solution { public: int candy(vector<int>& ratings) { int n = ratings.size(); vector<int> left(n, 0); vector<int> right(n, 0); /* walk from left to right, if current rating increase than previous one, then the current sweets should be one more than previous one, otherwise, the current sweet should be one */ left[0] = 1; for(int i=1; i<n; i++){ if (ratings[i] > ratings[i-1]){ left[i] = left[i-1] + 1; } else { left[i] = 1; } } /* walk from right to left, if current rating increase than previous one, then the current sweets should be one more than previous one, otherwise, the current sweet should be one */ right[n-1] = 1; for(int i=n-2; i>=0; i--){ if (ratings[i] > ratings[i+1]){ right[i] = right[i+1] + 1; } else { right[i] = 1; } } /* for each positon, the deserved sweets should be met by rule: greater than left and greater than right */ int ans = 0; for(int i=0; i<n; i++){ ans += max(left[i], right[i]); } return ans; } };
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。