【LC刷题】DAY23:455 376 53
455. 分发饼干 link
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int m = g.size(), n = s.size();
int count = 0;
for(int i = 0, j = 0; i < m && j < n; i ++, j ++){
while(j < n && g[i] > s[j]){
j ++;
}
if(j < n){
count ++;
}
}
return count;
}
};
376. 摆动序列 link
class Solution {
public:
int dp[1005][2];
int wiggleMaxLength(vector<int>& nums) {
memset(dp, 0, sizeof dp );
dp[0][0] = dp[0][1] = 1;
for(int i = 1; i < nums.size(); i++){
dp[i][0] = dp[i][1] = 1;
for(int j = 0; j < i; j ++){
if(nums[j]>nums[i]) dp[i][1] = max(dp[i][1], dp[j][0] + 1);
}
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]) dp[i][0] = max(dp[i][0], dp[j][1]+ 1);
}
}
return max(dp[nums.size() - 1][0], dp[nums.size() - 1][1]);
}
};
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() <= 1) return nums.size();
int curDiff = 0;
int preDiff = 0;
int result = 1;
for(int i = 0; i < nums.size() - 1; i ++){
curDiff = nums[i + 1] - nums[i];
if((preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0)){
result++;
preDiff = curDiff;
}
}
return result;
}
};
53. 最大子数组和 link
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = INT32_MIN;
int count = 0;
for (int i = 0; i < nums.size(); i++) { // 设置起始位置
count += nums[i];
if(count > result){
result = count;
}
if(count <= 0) count = 0;
}
return result;
}
};