121. 买卖股票的最佳时机(Java)(双指针)(单调队列)(动归正向迭代,二维dp及优化)

1 题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2 Java

2.1 方法一(理解为双指针)

i为索引遍历数组prices,记录并更新低价lowPrice、高价highPrice、最大利润maxProfit

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        int lowPrice = prices[0];
        int highPrice = prices[0];
        int maxProfit = 0;
        
        for(int i = 1; i < prices.length; i++){
        	// 若元素高于最高价
            if(prices[i] > highPrice) highPrice = prices[i];
            // 若元素低于最低价
            else if(prices[i] < lowPrice){
                maxProfit = Math.max(maxProfit, highPrice - lowPrice);
                lowPrice = prices[i];
                highPrice = prices[i];
            }
            // 若元素在最低价和最高价之间,不做操作
        }
        maxProfit = Math.max(maxProfit, highPrice - lowPrice);
        return maxProfit;
    }
}

注:
1、空数组与null不同,prices = []并不代表null,仅代表prices.length == 0
2、public int maxProfit(int[] prices) 这样的函数不能传入null,可以传入空数组[]
3、判断是否为空数组,只能用prices.length == 0,不能用prices == []

简化:

class Solution {
    public int maxProfit(int[] prices) {
        int buy = 0, sell = 0;
        int profit = 0;
        while(sell < prices.length){
            if(prices[buy] > prices[sell])  buy = sell;
            else    profit = Math.max(profit, prices[sell] - prices[buy]);
            sell++;
        }
        return profit;
    }
}

2.2 方法二(单调队列)

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)  return 0;

        LinkedList<Integer> q = new LinkedList<>();
        int ans = 0;
        for(int price: prices){
            // 若当前元素 < 队尾元素,弹出队尾
            while(!q.isEmpty() && q.peekLast() > price){
                ans = Math.max(ans, q.peekLast() - q.peek());
                q.removeLast();
            }
            q.add(price);
        }

        return Math.max(ans, q.peekLast() - q.peek());
    }
}

2.3 方法三(动归正向迭代,二维dp)

class Solution {
    /*
        dp[3][2][1] 的含义:今天是第3天,我现在手上持有着股票,至今最多进行 2 次交易
        dp[2][3][0] 的含义:今天是第2天,我现在手上没有持有股票,至今最多进行 3 次交易
    */

    public int maxProfit(int[] prices) {
        if(prices.length == 0)  return 0;
        // 创建初始化备忘录
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;   dp[0][1] = - prices[0];
        
        // 外层for状态步进
        for(int i = 1; i < prices.length; i++){
            // 内层for状态转移
            // 今天不持有;是一直没有/前几天卖了,还是今天卖?
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            // 今天持有;是前几天买入,还是今天买入?
            dp[i][1] = Math.max(dp[i - 1][1], - prices[i]);
        }

        return dp[prices.length - 1][0];
    }
}

for内初始化dp

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)  return 0;

        // 创建 dp;!!!初始化复杂,放在 for 中
        int[][] dp = new int[prices.length][2];
        // 外层for,状态步进
        for(int i = 0; i < prices.length; i++){
            // 初始化dp
            if(i == 0){
                dp[0][0] = 0;
                dp[0][1] = - prices[0];
                continue;
            }
            // 内层for,状态转移,多路择优
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], 0 - prices[i]);
            // !!!注意是 0-prices[i],因为 k=1 只有一次买卖机会
        }

        return dp[prices.length - 1][0];
    }
}

2.4 方法四(动归正向迭代,二维dp优化)

class Solution {
    /*
        dp[3][2][1] 的含义:今天是第3天,我现在手上持有着股票,至今最多进行 2 次交易
        dp[2][3][0] 的含义:今天是第2天,我现在手上没有持有股票,至今最多进行 3 次交易
    */

    public int maxProfit(int[] prices) {
        if(prices.length == 0)  return 0;
        // 创建初始化备忘录
        //int[][] dp = new int[prices.length][2];
        //dp[0][0] = 0;   dp[0][1] = - prices[0];
        int dp_i_0 = 0, dp_i_1 = - prices[0];
        
        // 外层for状态步进
        for(int i = 1; i < prices.length; i++){
            // 内层for状态转移
            // 今天不持有;是一直没有/前几天卖了,还是今天卖?
            //dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
            // 今天持有;是前几天买入,还是今天买入?
            //dp[i][1] = Math.max(dp[i - 1][1], - prices[i]);
            dp_i_1 = Math.max(dp_i_1, - prices[i]);
        }

        return dp_i_0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值