Best Time to Buy and Sell Stock III

来源:互联网 发布:今古传奇故事 知乎 编辑:程序博客网 时间:2024/05/21 14:45

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问题,能买2次(第一次的卖可以和第二次的买在同一时间),但第二次的买不能在第一次的卖左边。

利用left数组来存【0, i】的最大利润,每次需要保存左侧最小的价格min_price,然后left【i】= max(left【i-1】,prices【i】-min_prices)

然后再从右往左,利用right数组保存【i, n】的最大利润。每次需要保存右侧最大的价格max_price, 然后right【i】= max(right【i+1】,max_prices - prices【i】)


int maxProfit(vector<int> &prices){    if (prices.size() == 0)        return 0;    int profit = 0, n = prices.size();    int left[n], right[n];    memset(left, 0, sizeof(int) * n);    memset(right, 0, sizeof(int) * n);    int min_price = prices[0];    for (int i = 1; i < n; i++)    {        left[i] = max(prices[i] - min_price, left[i - 1]);        min_price = min(prices[i], min_price);    }    int max_price = prices[n - 1];    for (int i = n - 2; i >= 0; i--)    {        right[i]= max(max_price - prices[i], right[i + 1]);        max_price = max(prices[i], max_price);    }    for (int i = 0; i < n; i++)    {        profit = max(left[i] + right[i], profit);    }    return profit;}


0 0
原创粉丝点击