zoukankan      html  css  js  c++  java
  • 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;
    	}
    };
    
    

    我的视频题解空间

    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    记RestTemplate远程请求接口数据的一些注意事项
    记使用SpringDataMongonDb时,dao方法命名的一个已解决但不知道为什么的bug
    charles 打断点后传参或返回数据更改
    在liunx上搭建git仓库1
    jsonpath 提取参数
    pytest 参数化的使用1
    pytest中断言失败后,也可以继续执行其他用例
    charles开启弱网功能
    httprunner 参数化
    httprunner中debugtalk使用
  • 原文地址:https://www.cnblogs.com/itdef/p/15033247.html
Copyright © 2011-2022 走看看