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

 

Code:

Method1:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int oneTry=0,oneHis=0,twoTry=0,twoHis=0; //Try: attempt to buy; His: the max-profit record; One/Two: one/two transaction(s)
        int n = prices.size() - 1;
        for (int i=0;i<n;i++){ 
            int diff = prices[i+1] - prices[i];
            if(i>0){
                twoTry = max(twoTry, oneHis) + diff;
                twoHis = max(twoTry,twoHis); // the max-profit by totally two transactions
            }
            oneTry = max(oneTry, 0) + diff;
            oneHis = max(oneTry,oneHis); // the max-profit by totally one transaction
        }
        return max(oneHis,twoHis);
    }
};

 

Method2:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // null check
        int len = prices.size();
        if (len==0) return 0;

        vector<int> historyProfit;
        vector<int> futureProfit;
        historyProfit.assign(len,0);
        futureProfit.assign(len,0);
        int valley = prices[0];
        int peak = prices[len-1];
        int maxProfit = 0;

        // forward, calculate max profit until this time
        for (int i = 0; i<len; ++i)
        {
            valley = min(valley,prices[i]);
            if(i>0)
            {
                historyProfit[i]=max(historyProfit[i-1],prices[i]-valley);
            }
        }

        // backward, calculate max profit from now, and the sum with history
        for (int i = len-1; i>=0; --i)
        {
            peak = max(peak, prices[i]);
            if (i<len-1)
            {
                futureProfit[i]=max(futureProfit[i+1],peak-prices[i]);
            }
            maxProfit = max(maxProfit,historyProfit[i]+futureProfit[i]);
        }
        return maxProfit;
    }
};

 

转载于:https://www.cnblogs.com/winscoder/p/3398375.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值