https://oj.leetcode.com/problems/candy/
/* * *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: **Each child must have at least one candy. **Children with a higher rating get more candies than their neighbors. *What is the minimum candies you must give?*题目大概意思就是给你一些孩子的rating,这些孩子站成一个直线。相邻的孩子rating高的一定要比rating低的孩子的candy多 *全部孩子至少有一个candy。
*/ #include <iostream> #include <vector> using namespace std; class Solution { public: int candy(vector<int> &ratings) { const int size = ratings.size(); vector<int> ratingValue(size, 1); int i = 0; int k = 1; //从左往右扫瞄一次。波谷为1。然后依次加1到波峰,再到波谷时又是1 for(i = 1; i < size; i++){ if(ratings[i] > ratings[i - 1]){ ratingValue[i] = max(ratingValue[i], ++k); } else { //从波峰到波谷时,不改变ratingValue,仅仅是置K值 k = 1; } } //同理。从右往左扫瞄一次,波谷为1,然后依次加1到波峰 k = 1; for(i = size - 2; i >= 0; i--){ if(ratings[i] > ratings[i + 1]){ ratingValue[i] = max(ratingValue[i], ++k); } else { k = 1; } } int sumCandy = 0; for(i = 0; i < size; i++){ sumCandy = sumCandy + ratingValue[i]; } return sumCandy; } }; int main(){ Solution solution; int array[8] = {6, 3, 2, 8, 7, 6, 9, 4}; vector<int> ratings(array, array+7); cout<<solution.candy(ratings)<<endl; }</span>
版权声明:本文博客原创文章,博客,未经同意,不得转载。