一、问题描述:
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?
https://leetcode.com/problems/candy/
二、解题思路:
这是一道局部贪心问题,对整个数组划分成多个严格单调递增和严格单调递减的组合区间,每个区间内部使用分最少糖果策略。需要值得注意的是需要考虑区间首元素和上一区间的末元素大小问题,如果该元素小于等于上一区间的的末元素,则赋1即可,否则需要赋2。
三、代码:beats 90% submissions in c++ =。=
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <fstream>
#define PI (acos(-1.0))
#define EPS (1e-8)
#define INF (1<<30)
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
if (ratings.size() <= 1) return ratings.size();
int left=0, right=0, pos=0, n=ratings.size(), sum=0;
while(left < n) {
int i, lval = 1, rval;
if(left!=0 && ratings[left]>ratings[left-1]) lval++;
for(i = left+1; i<n && ratings[i]>ratings[i-1]; i++) {// gradient increase
sum += lval;
if (ratings[i] > ratings[i-1]) lval++;
}
pos = --i; // find local max
for(right = i+1; right<n && ratings[right]<ratings[right-1]; right++); // gradient decrease
right--; // right point to the last local decrease element
// cout << "left: " << left << ", pos: " << pos << ", right: " << right << endl;
for(i = right, rval = 1; i > pos; i--) {
sum += rval;
if (ratings[i] < ratings[i-1]) {
rval++;
}
}
sum += max(max(lval, rval), 1);
// cout << "sum: " << sum << ", lval: " << lval << ", rval: " << rval << endl;
left = right+1;
}
return sum;
}
};
int main(int argc, char const *argv[]) {
int cnt, x;
Solution solu;
vector<int> v;
cin >> cnt;
while(cnt--) {
cin >> x;
v.push_back(x);
}
cout << solu.candy(v) << endl;
return 0;
}