#151 Best Time to Buy and Sell Stock III

来源:互联网 发布:糯米商家怎么收费知乎 编辑:程序博客网 时间:2024/06/05 22:38

题目描述:

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.

 Notice

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example [4,4,6,1,1,4,2,5], return 6.

题目思路:

这题的思路和#149一样。刚开始的时候我想把149的函数直接拿过来用,对于每个i都两边算一个single max profit,然后求得交易两次的profit。这个方法可行,可是时间代价是O(n^2)完全不能accept。

这题根据forward-backward traversal的提示,应该想到不但max/min number可以这么干,profit也可以用同样的思路求:对于每个i,可以左边求一个profit,右边求一个profit,然后两边相加看哪个i对应的总和最大。

例如左边求profit,需要一个left_min数组记录i往左的最小值,i是当前的price,而且永远在最小值左边。这样,一直往右遍历i,找到prices[i] - left_min[i]的最大值就可以了。

Mycode(AC = 39ms):

class Solution {public:    /**     * @param prices: Given an integer array     * @return: Maximum profit     */    int maxProfit(vector<int> &prices) {        // write your code here        if (prices.size() <= 1) return 0;                vector<int> left_min(prices), left_profit(prices.size(), 0);        vector<int> right_max(prices), right_profit(prices.size(), 0);                // get left min and left profit        for (int i = 1; i < prices.size(); i++) {            left_min[i] = min(left_min[i - 1], prices[i]);            left_profit[i] = max(left_profit[i - 1], prices[i] - left_min[i]);        }                // get right max and right profit        for (int i = prices.size() - 2; i >= 0; i--) {            right_max[i] = max(right_max[i + 1], prices[i]);            right_profit[i] = max(right_profit[i + 1], right_max[i] - prices[i]);        }                 int profit = 0;        for (int i = 0; i < prices.size(); i++) {            profit = max(profit, left_profit[i] + right_profit[i]);        }                return profit;    }};


0 0
原创粉丝点击