zoukankan      html  css  js  c++  java
  • 0123. Best Time to Buy and Sell Stock III (H)

    Best Time to Buy and Sell Stock III (H)

    题目

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    Example 1:

    Input: [3,3,5,0,0,3,1,4]
    Output: 6
    Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
                 Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
    

    Example 2:

    Input: [1,2,3,4,5]
    Output: 4
    Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
                 Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
                 engaging multiple transactions at the same time. You must sell before buying again.
    

    Example 3:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.
    

    题意

    在一个时刻买入股票,在另一个时刻卖出股票,最多可进行2次交易,求能得到的最大收益。

    思路

    和 0121 很像,只是限定了最多两次交易。可以在0121的基础上进行改进:将数组分成左右两个子数组A(1 -> k)和B(k+1 -> n),分别找到最大收益并相加,改变k找到最大的和就是答案。但这样做有一个问题,即没有考虑A中买入B中卖出的情况。继续改进,我们给A中的最大收益加上一个限制,即必须在第k天卖出,这样第二次交易就能完全落在B中。


    代码实现

    Java

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0) {
                return 0;
            }
    
            int profit = 0;
            int minLeft = prices[0];
            int maxRight = prices[prices.length - 1];
            int[] pRightMax = new int[prices.length];
    
            // 找到从i开始的右区间能得到的最大收益
            for (int i = prices.length - 2; i >= 0; i--) {
                pRightMax[i] = Math.max(pRightMax[i + 1], maxRight - prices[i]);
                maxRight = Math.max(maxRight, prices[i]);
            }
    
            for (int i = 1; i < prices.length; i++) {
                // prices[i]-minLeft 为左区间在第i天卖出能得到的最大收益
                if (prices[i] - minLeft >= 0) {
                    profit = Math.max(profit, prices[i] - minLeft + (i == prices.length - 1 ? 0 : pRightMax[i + 1]));
                }
                minLeft = Math.min(minLeft, prices[i]);
            }
    
            return profit;
        }
    }
    
  • 相关阅读:
    super的使用
    Django--自定义 Command 命令
    Django models
    二柱子的编程 四则运算2
    阅读《梦断代码》计划
    随机数计算小学四则运算
    人月神话有感
    软件演化
    软件测试
    软件实现
  • 原文地址:https://www.cnblogs.com/mapoos/p/13517368.html
Copyright © 2011-2022 走看看