力扣(LeetCode) 122.买卖股票的最佳时机 二(java)

题目

方法一:动态规划

public class MaxProfit2 {

    public int maxProfit(int[] prices) {
        //动态规划
        //每天都有持有和不持有之分,设dp[i][0]持有的利润,dp[i][1]不持有的利润。
        //持有分两种情况 1、前天持有今天不操作即 dp[i-1][0]。2、前天不持有今天买入即(可以多次交易,之前可能会存在交易,故前天不持有可能会有利润)dp[i-1][1] - prices[i]。
        //dp[i][0] = max(dp[i-1][0], - prices[i])
        //不持有分两种情况 1、前天不持有今天不操作即 dp[i-1][1]。2、前天持有今天卖出即 dp[i-1][0] + prices[i]。
        //dp[i][1] = max(dp[i-1][1], (dp[i-1][0] + prices[i]))
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        int dp[] = new int[2];
        dp[0] = -prices[0];
        dp[1] = 0;
        //System.out.println(dp[0][0]+" "+dp[0][1]);
        for (int i = 1; i < len; i++) {
            dp[0] = Math.max(dp[0], dp[1]-prices[i]);
            dp[1] = Math.max(dp[1], dp[0]+prices[i]);
            System.out.println(dp[0]+" "+dp[1]);
        }

        return dp[1];
    }

    public static void main(String[] args) {
        MaxProfit2 maxProfit = new MaxProfit2();
        int[] prices = {7,1,5,3,6,4};
        //int[] prices = {7,6,4,3,1};
        System.out.println(maxProfit.maxProfit(prices));
    }

}

 LeetCode测试结果

方法二:贪心

public class MaxProfit2 {

    public static void main(String[] args) {
        MaxProfit2 maxProfit = new MaxProfit2();
        //int[] prices = {7,1,5,3,6,4};
        //int[] prices = {7,6,4,3,1};
        int[] prices = {1,2,3,4,5};
        System.out.println(maxProfit.maxProfit(prices));
    }

    public int maxProfit(int[] prices) {
        //贪心 有利润买卖
        int len = prices.length;
        int max = 0;
        for (int i = 1; i < len; i++) {
            if (prices[i] > prices[i-1]) {
                max += prices[i] - prices[i-1];
            }
        }
        return max;
    }

}

 LeetCode测试结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值