leetcode Best Time to Buy and Sell Stock III

231 篇文章 0 订阅

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 twotransactions.

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.

 

I was influenced by the last question. First, I found all starting points and ending points of ascending status as depicted in the last question. However,  these pairs should be divided into two parts. For every part, we needed to find the most ascending sequence. But, the code was written in a lengthy and wrong way.  Even if it was finished, the complexity is o(n^2)

 

 

A solution from my classmate. We could use profit[0][i] to record the maximum profit from 0 to i and profit[1][i] to record the maximum profit from j to end. So it's a dynamic problem, which could be solved in O(n) time. 

 

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int i,j,res=0,buy,sell;
        vector<int> profit[2];;	
        if(prices.size()==0)            return 0;
        else{
            buy=prices[0];
			profit[0].push_back(0);
            for(i=1;i<prices.size();i++){
				if(prices[i]<buy){
					profit[0].push_back(profit[0][i-1]);
					buy=prices[i];
				}
				else{
					if(prices[i]-buy>profit[0][i-1])
						profit[0].push_back(prices[i]-buy);
					else
						profit[0].push_back(profit[0][i-1]);
				}
            }
			sell=prices[prices.size()-1];
			profit[1].push_back(0);
			for(i=prices.size()-2;i>=0;i--){
				if( prices[i]>sell ){
					profit[1].push_back( profit[1][profit[1].size()-1] );
					sell=prices[i];
				}	
				else{
					if( sell-prices[i]>profit[1][profit[1].size()-1] )
						profit[1].push_back(sell-prices[i]);
					else
						profit[1].push_back(profit[1][profit[1].size()-1]);
				}
			}	

			for(i=0;i<profit[0].size();i++){
				if( profit[0][i]+profit[1][profit[0].size()-1-i]>res )
					res=profit[0][i]+profit[1][profit[0].size()-1-i];
			}
         }
		 return res;
    }
};

Python Version:

class Solution:
    def maxProfit(self, prices):
        plen = len(prices)
        if (plen <= 0):
            return 0
        sellAtI,buyAtI = [0 for i in range(plen)], [0 for i in range(plen)]

        leftLeast, rightLargest = prices[0], prices[plen-1]
        for i in range(1, plen):
            if (prices[i] < leftLeast):
                leftLeast = prices[i]
            sellAtI[i] = max(prices[i]-leftLeast, sellAtI[i-1])

        for i in range(plen-2, 0, -1):
            buyAtI[i] = max(buyAtI[i+1],rightLargest-prices[i])
            if (prices[i] > rightLargest):
                rightLargest = prices[i]

        res = 0
        for i in range(plen):
            res = max(res, sellAtI[i]+buyAtI[i])
        return res
s = Solution()
print(s.maxProfit([3,3,5,0,0,3,1,4]))
print(s.maxProfit([1,2,3,4,5]))
print(s.maxProfit([7,6,4,3,1]))

Stateful DP Version:

class Solution:
    def maxProfit(self, prices) -> int:
        # t[i][j][0] stands for ith day, j transactions, no stocks on hands
        # t[i][j][1] stands for ith day, j transactions, with stocks on hands

        # t[i][j][0] = max(t[i-1][j][0], t[i-1][j-1][1]+prices[i])
        # t[i][j][1] = max(t[i-1][j][1], t[i-1][j][0]-prices[i])

        l = len(prices)
        if (l <= 1):
            return 0

        t = [[[0 for k in range(2)] for j in range(3)] for i in range(l)]
        t[0][0][1] = t[0][1][1] = t[0][2][1] = -prices[0]

        for i in range(1, l):
            for j in range(3):
                t[i][j][0] = max(t[i - 1][j][0], t[i - 1][j - 1][1] + prices[i]) if (j >= 1) else 0
                t[i][j][1] = max(t[i - 1][j][1], t[i - 1][j][0] - prices[i])

        return max(t[l - 1][2][0], t[l - 1][1][0], 0)

s = Solution()
print(s.maxProfit([7,6,4,3,1]))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值