[LeetCode-123] Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III

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

 

储存0-N天的最大收益和N-END天的最大收益就好。

 

 1 class Solution {
 2     public:
 3         int maxProfit(vector<int> &prices) {
 4             // Start typing your C/C++ solution below
 5             // DO NOT write int main() function
 6             int day_cnt = prices.size();
 7             if (day_cnt < 2) {
 8                 return 0;
 9             }
10             vector<vector<int> > profits;
11             vector<int> profits_02N(day_cnt, 0);
12             vector<int> profits_N2E(day_cnt, 0);
13             int last_min = INT_MAX, last_max = 0, tmp_profit = 0, max_profit = 0;
14  
15             for (int i = 0; i < day_cnt; ++i) {
16                 if (prices.at(i) < last_min) {
17                     last_min = prices.at(i);
18                 } else {
19                     tmp_profit = max<int>(tmp_profit, prices.at(i) - last_min);
20                 }  
21                 profits_02N[i] = tmp_profit;
22             }  
23             tmp_profit = 0;
24             for (int i = day_cnt - 1; i >= 0; --i) {
25                 if (prices.at(i) > last_max) {
26                     last_max = prices.at(i);
27                 } else {
28                     tmp_profit = max<int>(tmp_profit, last_max - prices.at(i));
29                 }
30                 profits_N2E[i] = tmp_profit;
31             }
32            
33             max_profit = profits_02N[day_cnt - 1];
34             for (int i = 0; i < day_cnt - 1; ++i) {
35                 tmp_profit = profits_02N[i] + profits_N2E[i + 1];;
36                 if (tmp_profit > max_profit) {
37                     max_profit = tmp_profit;
38                 }
39             }
40             return max_profit;
41         }
42 };
View Code

 

posted on 2013-08-29 08:43  似溦若岚  阅读(168)  评论(0编辑  收藏  举报

导航