Best Time to Buy and Sell Stock III

Q:

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

A:

相当于找一个点,该点将数组分为两部分,这两部分分别求最大利润,求最大的两者之和。

由左至右遍历一遍,保存一个数组,该数组中每个数的含义是,从原始数组的最左边到该位置能获得的最大利润

由右至左遍历一遍,保存一个数组,该数组中每个数的含义是,从原始数组的最右边到该位置能获得的最大利润

然后找某个点对应的最大直,搞定。

class Solution {
 public:
  int maxProfit(vector<int> &prices) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function
    int max_prefit = 0;
    int len = prices.size();
    if (len <= 1) return 0;
    vector<int> max_prefit_l;
    max_prefit_l.resize(len);
    vector<int> max_prefit_r;
    max_prefit_r.resize(len);

    int cur_min = 0;
    int cur_max_prefit = 0;
    for (int i = 0; i < len; ++i) {
      if (prices[cur_min] > prices[i]) {
        cur_min = i;
      }   
      if (prices[i] - prices[cur_min] > cur_max_prefit) {
        cur_max_prefit = prices[i] - prices[cur_min];
      }   
      max_prefit_l[i] = cur_max_prefit;
    }   

    int cur_max = len - 1;
    cur_max_prefit = 0;
    for (int i = len - 1; i >= 0; --i) {
      if (prices[cur_max] < prices[i]) {
        cur_max = i;
      }   
      if (prices[cur_max] - prices[i] > cur_max_prefit) {
        cur_max_prefit = prices[cur_max] - prices[i];
      }   
      max_prefit_r[i] = cur_max_prefit;
      if (i - 1 >= 0 && max_prefit_l[i - 1] > 0) {
        max_prefit = max(max_prefit_r[i] + max_prefit_l[i - 1], max_prefit);
      } else {
        max_prefit = max(max_prefit_r[i], max_prefit);
      }   
    }   
    return max_prefit;
  }
};

 

posted @ 2013-06-24 21:05  dmthinker  阅读(122)  评论(0)    收藏  举报