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

Posted

tags:

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

 

 

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

 

动态规划,preprofit保存i之前交易获得的收益。postprofit保存i之后交易获得的收益。

max{preprofit[i]+postprofit[i]}既是最大的可能收益。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size=prices.size();
        if (size<2)
            return 0;
        int curmin=prices[0],curmax=prices[size-1];
        vector<int> preProfit(size,0);
        vector<int> postProfit(size,0);
        for(int i=1;i<size;i++){
            curmin=min(curmin,prices[i]);
            preProfit[i]=max(preProfit[i-1],prices[i]-curmin);
        }
        for (int j = size-1;j>0; --j){
            curmax=max(curmax,prices[j]);
            postProfit[j]=max(postProfit[j-1],curmax-prices[j]);

        }
        int retProfit=0;
        for(int m=0;m<size;m++){
            if(retProfit<(preProfit[m]+postProfit[m]))
                retProfit=preProfit[m]+postProfit[m];
        }
        return retProfit;
    }
};

 

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

123. Best Time to Buy and Sell Stock leetcode解题笔记

[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