理論基礎
https://programmercarl.com/貪心演算法理論基礎.html
455.分發餅乾
https://programmercarl.com/0455.分發餅乾.html
var findContentChildren = function (g, s) {
g = g.sort((a, b) => a - b);
s = s.sort((a, b) => a - b);
let result = 0;
let index = s.length - 1;
for (let i = g.length - 1; i >= 0; i--) {
if (index >= 0 && s[index] >= g[i]) {
result++;
index--;
}
}
return result;
};
- 擺動序列
https://programmercarl.com/0376.擺動序列.html
比較難
/**
* @param {number[]} nums
* @return {number}
*/
var wiggleMaxLength = function(nums) {
let len = nums.length;
if (len<=1) return len;
let preDiff = 0;
let curDiff = 0;
let result = 1;
for (let i=0;i<len-1;i++) {
curDiff = nums[i+1] - nums[i];
if ((preDiff<=0 && curDiff>0) || (preDiff>=0 && curDiff<0)) {
result++;
preDiff = curDiff;
}
}
return result;
};
- 最大子序和
https://programmercarl.com/0053.最大子序和.html
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let result = -Infinity;
let count = 0;
for (let i=0;i<nums.length;i++) {
count += nums[i];
if (count>result) {
result = count;
}
if (count<0) count=0;
}
return result;
};