Leetcode 135. 分发糖果

地址 https://leetcode-cn.com/problems/candy/

老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
你需要按照以下要求,帮助老师给这些孩子分发糖果:
每个孩子至少分配到 1 个糖果。
评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。
那么这样下来,老师至少需要准备多少颗糖果呢?

示例 1:
输入:[1,0,2]
输出:5
解释:你可以分别给这三个孩子分发 2、1、2 颗糖果。

示例 2:
输入:[1,2,2]
输出:4
解释:你可以分别给这三个孩子分发 1、2、1 颗糖果。
     第三个孩子只得到 1 颗糖果,这已满足上述两个条件。

解答
贪心 左右扫描两边保证条件“评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。” 尽量糖果数字下
我这里使用的是按照评分排序 尽量少的满足评分小的孩子 再去推断评分大的孩子的糖果
由于使用了排序 时间没有达到O(n) 但是也可以作为一种参考
image

class Solution {
public:
	vector<pair<int, int>> vv;
	int candy(vector<int>& ratings) {
		for (int i = 0; i < ratings.size(); i++) {
			vv.push_back({ ratings[i],i });
		}
		sort(vv.begin(),vv.end());
		int ans = 0;
		vector<int> getCandy(ratings.size());
		for (auto& p : vv) {
			int score = p.first;
			int idx = p.second;

			int left = 0;  int right = 0;
			if (idx - 1 >= 0 && getCandy[idx - 1] != 0 && score > ratings[idx - 1]) { left = getCandy[idx - 1] + 1; }
			if (idx + 1 < getCandy.size() && getCandy[idx + 1] != 0 && score > ratings[idx + 1]) { right =  getCandy[idx + 1] + 1; }

			int candCount = max(left, right);
			if (candCount == 0) candCount++;

			getCandy[idx] = candCount;
			ans += candCount;
		}


		return ans;
	}
};

我的视频题解空间

posted on 2021-07-20 09:14  itdef  阅读(61)  评论(0编辑  收藏  举报

导航