Two notes:

1. result at least n candys. Use array scan from beginning and from end.

2. dp[i] = max(dp[i], count++). count++ already record the increasing sequence, dont have to compare with dp[i+1] (or dp[i-1]) + 1

 

 1 class Solution {
 2 public:
 3     int candy(vector<int> &ratings) {
 4         int len = ratings.size(), result = len;
 5         if (len < 2) return len;
 6         vector<int> dp(len, 0);
 7         for (int i = 0, count = 1; i < len; i++) {
 8             if (i > 0 && ratings[i] > ratings[i-1]) {
 9                 dp[i] = max(dp[i], count++);
10             } else {
11                 count = 1;
12             }
13         }
14         for (int i = len-1, count = 1; i >= 0; i--) {
15             if (i < len-1 && ratings[i] > ratings[i+1]) {
16                 dp[i] = max(dp[i], count++);
17             } else {
18                 count = 1;
19             }
20         }
21         for (int i = 0; i < len; i++) {
22             result += dp[i];
23         }
24         return result;
25     }
26 };

 

posted on 2015-03-18 09:22  keepshuatishuati  阅读(91)  评论(0编辑  收藏  举报