455.分发饼干
题目链接:455.分发饼干
文档链接:455.分发饼干
视频链接:贪心算法,你想先喂哪个小孩?| LeetCode:455.分发饼干
C++实现
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int result = 0;
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int Index = s.size()-1;
for(int i = g.size() - 1; i >= 0; i--){
if(Index >= 0 && g[i] <= s[Index]){
result++;
Index--;
}
}
return result;
}
};
376. 摆动序列
题目链接:376. 摆动序列
文档链接:376. 摆动序列
视频链接:贪心算法,寻找摆动有细节!| LeetCode:376.摆动序列
C++实现
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() <= 1) return nums.size();
int result = 1;
int curdiff = 0;
int prediff = 0;
for(int i = 0; i < nums.size() - 1; i++){
curdiff = nums[i+1] - nums[i];
if((curdiff > 0 && prediff <= 0) || (curdiff < 0 && prediff >= 0)){
result ++;
prediff = curdiff;
}
}
return result;
}
};
53. 最大子序和
题目链接:53. 最大子序和
文档链接:53. 最大子序和
视频链接:贪心算法的巧妙需要慢慢体会!LeetCode:53. 最大子序和
C++实现
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0;
int maxsum = INT32_MIN;
for(int i = 0; i < nums.size(); i++){
sum += nums[i];
if(sum > maxsum) {
maxsum = sum;
}
if(sum <= 0){
sum = 0;
}
}
return maxsum;
/*
if(nums.size() == 0) return 0;
vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
int result = dp[0];
for(int i = 1; i<nums.size(); i++){
dp[i] = max(dp[i - 1] + nums[i] , nums[i]);
if(result < dp[i]){
result = dp[i];
}
}
return result;
*/
}
};