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;
        }
    }
    
  • 相关阅读:
    共享文件时提示“将安全性信息应用到以下对象时发生错误”
    ROS 5.x自动定时备份并发送到邮箱(实用)
    Android检测网络是否正常代码!
    win7提示“User Profile Service服务未能登录”
    Android-修改TabWidget字体大小颜色及对齐
    Android 实现分页(使用TabWidget/TabHost)
    解决在ScrollView中套用ListView显示不正常
    Android中finish掉其它的Activity
    Android中如何控制元素的显示隐藏?
    <jQuery> 十一. 基本动画(显示, 隐藏, 滑入, 滑出, 淡入淡出)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13517368.html
Copyright © 2011-2022 走看看