第八章 贪心算法 part01
大纲
● 理论基础
● 455.分发饼干
● 376. 摆动序列
● 53. 最大子序和
理论基础
- 灵活应答
leetcode 455
分发饼干
class Solution {
public int findContentChildren(int[] g, int[] s) {
int res = 0;
Arrays.sort(g);
Arrays.sort(s);
for (int i = 0, j = 0; i < g.length && j < s.length; j++) {
if (g[i] <= s[j]) {
res++;
i++;
}
}
return res;
}
}
leetcode 376
摆动序列
class Solution {
public int wiggleMaxLength(int[] nums) {
int up = 1, down = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) up = down + 1;
else if (nums[i] < nums[i - 1]) down = up + 1;
}
return Math.max(up, down);
}
}
leetcode 53
最大子序和
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0, res = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
res = res > sum ? res : sum;
if (sum < 0) sum = 0;
}
return res;
}
}