Leetcode 135. 分发糖果

    xiaoxiao2022-07-07  149

    老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。

    你需要按照以下要求,帮助老师给这些孩子分发糖果:

    每个孩子至少分配到 1 个糖果。相邻的孩子中,评分高的孩子必须获得更多的糖果。

    那么这样下来,老师至少需要准备多少颗糖果呢?

    示例 1:

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

    示例 2:

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

     

    这道题按分数从小到达排序,然后从最小的分数,开始分配糖果。属于模拟的思路

    class Solution { public: int candy(vector<int>& ratings) { int n = ratings.size(); vector<int> res(n, 1); // 每个人先分配一个糖果 vector<pair<int,int>> helper; for(int i=0;i<n;i++){ helper.push_back({ratings[i],i}); } sort(helper.begin(),helper.end()); for(int i=1;i<n;i++){ if(helper[i].second!=0 && ratings[helper[i].second]>ratings[helper[i].second-1]) res[helper[i].second]=max(res[helper[i].second],res[helper[i].second-1]+1); if(helper[i].second!=n-1 && ratings[helper[i].second]>ratings[helper[i].second+1]) res[helper[i].second]=max(res[helper[i].second],res[helper[i].second+1]+1); } int count = 0; for(auto v:res){ count+=v; } return count; } };

     

    最新回复(0)