LeetCode 123: Best Time to Buy and Sell Stock III

来源:互联网 发布:mac os 10.9 dmg镜像 编辑:程序博客网 时间:2024/05/19 19:31

Difficulty: 4

Frequency: 2


Problem:

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

Solution:

class Solution {public:    int maxProfit(vector<int> &prices) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (prices.size() < 2)            return 0;        int * from_begin = new int[prices.size()];        int * from_end = new int[prices.size()];        int i_max_profit = 0, i_min = 0, i_max = 0;        from_begin[0] = 0;        from_end[prices.size() - 1] = 0;        for (int i = 1; i<prices.size(); ++i)        {            if (prices[i]>prices[i_max])            {                i_max = i;                i_max_profit = max(i_max_profit, (prices[i_max] - prices[i_min]));            }            else if(prices[i]<prices[i_min])            {                i_max = i_min = i;            }            from_begin[i] = i_max_profit;        }        i_max_profit = 0, i_min = i_max = prices.size() - 1;        for (int i = prices.size() - 2; i>=0; --i)        {            if (prices[i]<prices[i_min])            {                i_min = i;                i_max_profit = max(i_max_profit, (prices[i_max] - prices[i_min]));            }            else if(prices[i]>prices[i_max])            {                i_max = i_min = i;            }            from_end[i] = i_max_profit;        }        i_max_profit = 0;        for (int i = prices.size() - 1; i>=0; --i)        {            i_max_profit = max(i_max_profit, (from_end[i] + from_begin[i]));//See Notes. This is important.        }        delete [] from_begin;        delete [] from_end;        return i_max_profit;    }};


Notes:

Originally, I wrote max(i_max_profit, from_end[i] + from_begin[i-1]). This has two errors. First is i-1 should be i. Because we can sell it and then buy it in one day. The second is if without a() outside from_end[i] + from_begin[i-1] , it will cause runtime error. I guess it is because max is define as a macro using ?: operator, it has a low priority.

原创粉丝点击