令dp[i]表示第i个小朋友得到的糖果,初始化dp[i] = 1
如果ratings[i]>ratings[i-1],dp[i] = max(dp[i], dp[i-1]+1);
如果ratings[i]>ratings[i+1],dp[i] = max(dp[i], dp[i+1]+1);
遍历两次,第一次从左往右,第二次从右往左
注意处理边界,最终返回dp数组的元素和
时间复杂度O(N)
int candy(vector<int>& ratings) { // write code here int len = ratings.size(); vector<int> dp(len, 1); for(int i=1; i<len; ++i) { if(ratings[i]>ratings[i-1]) { dp[i] = max(dp[i], dp[i-1]+1); } } int res = dp[len-1]; for(int i=len-2; i>=0; --i) { if(ratings[i]>ratings[i+1]) { dp[i] = max(dp[i], dp[i+1]+1); } res += dp[i]; } return res; }