leetcode-123. Best Time to Buy and Sell Stock III

Posted 千念飞羽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-123. Best Time to Buy and Sell Stock III相关的知识,希望对你有一定的参考价值。

leetcode-123. Best Time to Buy and Sell Stock III

题目:

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 (ie, you must sell the stock before you buy again).’

和前2题不同,这里需要计算的是最多两次交易,而且要求不能同时拥有两个股票。

这题思路就是分治算法,从0到i天之内。每一天都可以将这段时间分割成为两个时间段,然后去求其最大值之和就好。
但是这里并不是简单的分治算法,因为两个问题不是是独立的,我们要求的是和。

这里不去思考最大2次交易而是来看最大k次交易。

我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。下面我们来看递推式,全局的比较简单,

global[i][j]=max(local[i][j],global[i-1][j]),

也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。对于局部变量的维护,递推式是

local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),

这是看了一篇博客介绍了答案来源

我自己没想出来

public class Solution 
    public int maxProfit(int[] prices)   
        if(prices==null || prices.length==0)  
            return 0;  
        int[] local = new int[3];  
        int[] global = new int[3];  
        for(int i=0;i<prices.length-1;i++)  
          
            int diff = prices[i+1]-prices[i];  
            for(int j=2;j>=1;j--)  
              
                local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);  
                global[j] = Math.max(local[j],global[j]);  
              
          
        return global[2];  
    

以上是关于leetcode-123. Best Time to Buy and Sell Stock III的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-123-Best Time to Buy and Sell Stock III]

LeetCode123 Best Time to Buy and Sell Stock III

LeetCode123 Best Time to Buy and Sell Stock III

leetcode 123. Best Time to Buy and Sell Stock III ----- java

[LeetCode] 123. Best Time to Buy and Sell Stock III Java

LeetCode 123. Best Time to Buy and Sell Stock III