贪心算法
题目链接:https://leetcode.com/problems/candy/description/
这道题目主要是思路,有了思路便很好办了。之前我始终不太理解贪心算法究竟是什么意思,然后思考一番加做题后发现其实是利用局部的资源最优来判断,比如说这道题目的比左右两边ratings高的candy更多,Kruskal算法的始终取不构成回环的权值最小边,都是贪心算法的体现
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candy(ratings.size(),1);
int num = 0;
for(int i = 0;i<candy.size()-1;++i)
{
if(ratings[i+1]>ratings[i])
candy[i+1] = candy[i] + 1;
}
for(int i = candy.size()-1;i>0;--i)
{
if(ratings[i-1]>ratings[i])
candy[i-1] = max(candy[i]+1,candy[i-1]);
}
for(int i = 0;i<candy.size();++i)
num += candy[i];
return num;
}
};