【代码随想录Day48】动态规划

文章提供了两种LeetCode题目——买卖股票的最佳时机I和II的解决方案,分别使用贪心算法和动态规划。对于I题,两种方法均找到最低价格并计算差值;对于II题,贪心方法累加所有正向差价,动态规划则维护持有和未持有状态的最大利润。
摘要由CSDN通过智能技术生成

121 买卖股票的最佳时机

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/

class Solution {  //贪心?直观做法
    public int maxProfit(int[] prices) {
        int minPrice = prices[0];
        int diff = 0;
        for (int price : prices) {
            if (price - minPrice > diff) {
                diff = price - minPrice;
            }
            minPrice = Math.min(minPrice, price);
        }
        return diff;
    }
}

class Solution { //DP
    public int maxProfit(int[] prices) {
        int hold = -prices[0];
        int unhold = 0;
        for (int i = 1; i < prices.length; i++) {
            hold = Math.max(hold, -prices[i]);        // 只能买一次体现在以前买的或者今天买的
            unhold = Math.max(unhold, hold + prices[i]);
        }
        return unhold;
    }
}

122 买卖股票的最佳时机II

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/

class Solution {  //贪心,收集正数的每天利润
    public int maxProfit(int[] prices) {
        int sum = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) sum += prices[i] - prices[i - 1];
        }
        return sum;
    }
}
class Solution { //dp
    public int maxProfit(int[] prices) {
        int hold = -prices[0];
        int unhold = 0;
        for (int i = 1; i < prices.length; i++) {
            int temp = hold;
            hold = Math.max(hold, unhold - prices[i]);
            unhold = Math.max(unhold, temp + prices[i]);
        }
        return unhold;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值