There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
What is the minimum candies you must give?
分析:
开始的时候想,找最小值,然后分两边计算,但是该想法不可取。
后来看答案,才知道,左右各扫描一遍,取最大值。
//方法一:左右各扫描一遍。时间复杂度 O(n) ,空间复杂度 O(n) class Solution { public: int candy(vector<int>& ratings) { const int N = ratings.size(); int cur = 1; vector<int> temp(N, 1); for(int i = 0; i <= N-2; i++) { if(ratings[i+1] > ratings[i]) temp[i+1] = ++cur; else cur = 1; } cur = 1; for(int i = N - 2; i >= 0; i--) { if(ratings[i+1] < ratings[i]) temp[i] = max(++cur, temp[i]); else cur = 1; } int sum = 0; for(int i = 0; i < N; i++) sum += temp[i]; return sum; } };
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46605771