1. 程式人生 > >LeetCode 123. Best Time to Buy and Sell Stock III (stock problem)

LeetCode 123. Best Time to Buy and Sell Stock III (stock problem)

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

分析

首先不壓縮空間的寫法,寫法依然參照stock problem精帖的base case ,分別用一個二維陣列去儲存sell和buy的狀況

const int inf=-999999;
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()<=1)
           return 0;
        int days=prices.size();
        int sell[days+1][3],buy[days+1][3];
        for(int i=0;i<3;i++){
            sell[0][i]=0;
            buy[0][i]=inf;
        }
        for(int i=0;i<=prices.size();i++){
            sell[i][0]=0;
            buy[i][0]=inf;
        }
        for(int i=1;i<=prices.size();i++){
            for(int k=1;k<=2;k++){
                sell[i][k]=max(sell[i-1][k],buy[i-1][k]+prices[i-1]);
                buy[i][k]=max(buy[i-1][k],sell[i-1][k-1]-prices[i-1]);
            }
        }
        return sell[prices.size()][2];
    }
};