#include <iostream> #include <vector> using namespace std; class Solution { public: int candy(vector<int> &ratings) { int last = 0; vector<int> candies(ratings.size(), 1); for(int i = 1; i < ratings.size(); ++i) { if(ratings[i] <= ratings[i - 1]) { int num = 1; for(int j = last; j < i; ++j) { candies[j] = num++; } last = i; } } int num = 1; for(int j = last; j < ratings.size(); ++j) { candies[j] = num++; } last = ratings.size() - 1; for(int i = ratings.size() - 2; i >= 0; --i) { if(ratings[i] <= ratings[i+ 1]) { int num = 1; for(int j = last; j > i; --j) { candies[j] = candies[j] > num ? candies[j] : num++; } last = i; } } num = 1; for(int j = last; j >=0; --j) { candies[j] = candies[j] > num ? candies[j] : num++; } int sum = 0; for(int i = 0; i < candies.size(); ++i) { sum+= candies[i]; } return sum; } }; int main(int argc, char *argv[]) { Solution s; vector<int> ratings{2,2,1}; std::cout << s.candy(ratings) << std::endl; return 0; }
6/01/2014
Leetcode -- Candy
Scan from both beginning and back, catch the strictly increasing and strictly decreasing ratings. When do the backward scan, be careful that if the current candy at location j is already greater than the expected candy, do not change it.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment