研习算法第十三站-贪心算法(javascript版)

243 阅读1分钟

贪心算法

  • 贪心算法是算法设计中的一种方法
  • 期盼通过每个阶段的局部最优解选择,从而达到最全局的最优
  • 结果不一定是最优的

使用场景

零钱兑换

可以得到最优解

image.png

得不到最优解

image.png

leetcode-cn.com 算法题实战

完整题目请打开 leetcode

455. 分发饼干

image.png

解题思路

  • 局部最优: 既能满足孩子,还消耗最少
  • 先将“较小的饼干”分给“胃口最小”的孩子
  • 对饼干数组和胃口数组升序排序
  • 遍历饼干数组,找到能满足第一个孩子的饼干
  • 然后继续遍历饼干数组,找到满足第二、三、...、n 个孩子的饼干
/**
 * @param {number[]} g
 * @param {number[]} s
 * @return {number}
 */
var findContentChildren = function(g, s) {
    const g1 = g.sort((a,b) => a-b)
    const s1 = s.sort((a,b) => a-b );
    let i = 0;
   
   s1.forEach(n => {
       // n 为饼干,不能满足就循环累计找到满足第一个孩子的
       if(n >= g1[i]) {
           i++
       }
   })
    return i;
};

122. 买卖股票的最佳时机 II

image.png

解题思路

  • 前提: 上帝视角,知道未来的价格
  • 局部最优: 见好就收,见差不动,不做任何操作
  • 新建一个变量,用来统计总利润。
  • 遍历价格数组,如果当前价格比昨天高,就在昨天买,今天卖,否则不交易
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let count =  0;
    for(let i = 1;i < prices.length; i++) {
        if(prices[i -1] < prices[i]) {
            count += prices[i] - prices[i -1]
        }
    }
    return count;
};