程式碼隨想錄演算法訓練營第31天 | 貪心演算法 455.分發餅乾 、376. 擺動序列、53. 最大子序和

YuanYF6發表於2024-06-10

理論基礎

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;
};
  1. 擺動序列

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;  
};
  1. 最大子序和

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;
};

相關文章