[LeetCode]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?

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值