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 (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 来分隔数组,那么只要计算出0~i 和 i ~ len-1这两个区间的最大和即可
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(!prices.size())
            return 0;
        
        /* 实际上等价于计算 0~i 和 i ~ len-1 的两个区间的最大和*/
        int len = prices.size();
        vector<int> sum(len,0);
        int maxPrompt = 0;
        int i = 0;
        
        /* border 在0~i的区间中,作为左边界取最小元素值  在i~len-1区间中作为右边界,取最大元素值 */
        int border = prices[0];
        
        /* 计算0~i区间的最大收益 */
        for(i = 1; i < len; i++ )
        {
            maxPrompt = max(maxPrompt, prices[i] - border);
            border = min(border, prices[i]);
            sum[i] = maxPrompt;
        }
        
        border = prices[len - 1];
        maxPrompt = 0;
        /*计算i~len-1区间的最大收益 */
        for(i = len-2 ; i >= 0; i--)
        {
            maxPrompt = max(maxPrompt, border - prices[i]);
            border = max(border, prices[i]);
            sum[i] += maxPrompt;
        }
        
        return *max_element(sum.begin(), sum.end());
    }
};

你可能感兴趣的:(数据结构与算法)