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

题目

 

 方法一:动态规划

public class MaxProfit {

    public int maxProfit(int[] prices) {

        //动态规划
        //每天都有持有和不持有之分,设dp[i][0]持有的利润,dp[i][1]不持有的利润。
        //持有分两种情况 1、前天持有今天不操作即 dp[i-1][0]。2、前天不持有今天买入即(只能交易一次,之前不会存在交易,故前天不持有不会有利润)-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[len][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        //System.out.println(dp[0][0]+" "+dp[0][1]);
        for (int i = 1; i < len; i++) {
            dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0]+prices[i]);
            System.out.println(dp[i][0]+" "+dp[i][1]);
        }

        return dp[len-1][1];

    }

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

}

 LeetCode测试结果

 方法二:滑动窗口

public class MaxProfit {

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

    public int maxProfit(int[] prices) {

        //滑动窗口
        //利润最大即 最低买入,最高卖出。
        //定义买入的最低值,定义卖出时获取的最大利润。
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int max = 0;

        for (int i = 0; i < len; i++) {
            if (min > prices[i]) {
                min = prices[i];
            } else if(min < prices[i] && max < prices[i] - min) {
                max = prices[i] - min;
            }

        }

        return max;
    }

}

 LeetCode测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值