LeetCode 122. 买卖股票的最佳时机 II java题解

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

dp

注释掉了dp数组,因为在某个用例时会超出内存。所以只用变量表示。

class Solution {
    public int maxProfit(int[] prices) {
        int len=prices.length;
        if(len==1) return 0;
        //int[][] dp=new int[len][len];//最大利润
        //[i][0]在今天不持有股票
        //[i][1]在今天持有股票
        //在同一天出售,没有任何意义啊,又没有差价
        //dp[0][0]=0;
        //dp[0][1]=-prices[0];
        int a=0,b=-prices[0];
        int max=0;//最大利润初始化为0
        for(int i=1;i<len;i++){
            //今天不持有:昨天不持有;昨天持有但今天卖掉了
            //dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i]); 
            int c=Math.max(a,b+prices[i]);
            //今天持有:昨天就持有;昨天没有但是今天买了
            //dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
            int d=Math.max(b,a-prices[i]);
            max=Math.max(max,Math.max(c,d));
            a=c;
            b=d;
        }
        return max;
    }
}

贪心

把利润分为每一天。每天只收集正利润。

// 贪心思路
class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
            result += Math.max(prices[i] - prices[i - 1], 0);
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值