第八部分 贪心算法
1. 理论基础
2. 分发饼干
var findContentChildren = function(g, s) {
g.sort((a, b) => a - b);
s.sort((a, b) => a - b);
const m = g.length, n = s.length;
let count = 0;
for (let i = 0, j = 0; i < m && j < n; i++, j++) {
while (j < n && g[i] > s[j]) {
j++;
}
if (j < n) {
count++;
}
}
return count;
};
3. 摆动序列
var wiggleMaxLength = function(nums) {
const n = nums.length;
if (n < 2) return n;
const up = new Array(n).fill(0);
const down = new Array(n).fill(0);
up[0] = down[0] = 1;
for (let i = 1; i < n; i++) {
if (nums[i] > nums[i - 1]) {
up[i] = Math.max(up[i - 1], down[i - 1] + 1);
down[i] = down[i - 1];
} else if (nums[i] < nums[i - 1]) {
up[i] = up[i - 1];
down[i] = Math.max(up[i - 1] + 1, down[i - 1]);
} else {
up[i] = up[i - 1];
down[i] = down[i - 1];
}
}
return Math.max(up[n - 1], down[n - 1]);
};
4. 最大子序和
var maxSubArray = function(nums) {
let pre = 0, maxAns = nums[0];
nums.forEach((x) => {
pre = Math.max(pre + x, x);
maxAns = Math.max(maxAns, pre);
});
return maxAns;
};