leetcode高频题笔记之贪心算法

本文总结了LeetCode中涉及贪心算法的题目,包括柠檬水找零、分发饼干、买卖股票等问题的贪心解法。通过案例分析了如何运用贪心策略解决问题,例如从后往前遍历优化跳跃游戏的步数,以及解决无重叠区间和最少箭引爆气球的问题。
摘要由CSDN通过智能技术生成

860.柠檬水找零

在这里插入图片描述
在20元找零处用到了贪心,贪10元的个数,如果有就先找10元+5元,没有再找三个5元

public class Solution {
   
    public boolean lemonadeChange(int[] bills) {
   
        int five = 0;
        int ten = 0;
        for (int bill : bills) {
   
            if (bill == 5) five++;//支付5元
            else if (bill == 10) {
   //支付10元
                if (five > 0) {
   //如果有5元的,找5元
                    five--;
                    ten++;
                } else {
   //如果没有5元的就无法找零退出
                    return false;
                }
            } else {
   //支付20元
                if (ten > 0 && five > 0) {
   //如果有10元和5元的,找10元+5元
                    ten--;
                    five--;
                } else if (ten == 0 && five >= 3) {
   //如果没有10元的有3张及以上5元的
                    five -= 3;
                } else//如果零钱不够,退出
                    return false;
            }
        }
        return true;
    }
}

455.分发饼干

在这里插入图片描述
将两个数组进行排序
从最小胃口的孩子和最小的饼干开始比较,如果不满足饼干后移一位,如果满足计数加一,饼干和小孩都后移一位

public class Solution {
   
    public int findContentChildren(int[] g, int[] s) {
   
        Arrays.sort(g);
        Arrays.sort(s);

        int i = 0;
        int j = 0;
        int count = 0;
        while (i < g.length && j < s.length) {
   
            if (g[i] <= s[j]) {
   
                count++;
                i++;
                j++;
            } else {
   
                j++;
            }
        }
        return count;
    }
}

121.买卖股票的最佳时机

在这里插入图片描述
遍历数组,如果值小于当前最小值更换当前最小值,如果值大于当前最小值和最小值做差更新最大差

public class Solution {
   
    public int maxProfit(int[] prices) {
   
        if (prices.length == 0) return 0;
        int max = 0;
        int minPrice = prices[0];
        for (int i = 1; i < prices.length; i++) {
   
            if (prices[i] < minPrice) minPrice = prices[i];
            else max = Math.max(prices[i] - minPrice, max);
        }
        return max;
    }
}

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

在这里插入图片描述
贪心:如果第二天大于第一天就第一天买第二天卖

public class Solution {
   
    public int maxProfit(int[] prices) {
   
      
        int res = 0;
        for (int i = 0; i < prices.length - 1; i++) {
   
            if (prices[i] < prices[i + 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值