Best Time to Buy and Sell Stock III

来源:互联网 发布:pc蛋蛋幸运28算法公式 编辑:程序博客网 时间:2024/05/21 05:59

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

思路:DP的思路,分别记录每个位置到目前为止的最大收益。从左边扫描一遍,每个位置记录的为这之前如果进行第一次交易的最大受益;再从右边扫描一遍,记录当前位置之后如果进行第二次交易的最大受益。然后取左右求和取最大值即可。

class Solution {public:    int maxProfit(vector<int> &prices) {        int size = prices.size();          if (size <= 1) {              return 0;          }                  vector<int> profit_left(size, 0);        vector<int> profit_right(size + 1, 0);                int low = prices[0];        int maxProfit = 0;        for (int i = 1; i < size; i++) {            profit_left[i] = max(profit_left[i - 1], prices[i] - low);            if (prices[i] < low) {                low = prices[i];            }        }                int high = prices[size-1];        for (int i = size - 2; i >= 0; i--) {            profit_right[i] = max(profit_right[i + 1], high - prices[i]);            if (prices[i] > high) {                high = prices[i];            }        }                for (int i = 0; i < size; i++) {            maxProfit = max(maxProfit, profit_left[i] + profit_right[i]);        }                        return maxProfit;    }};


0 0