-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBest Time to Buy and Sell Stock III.h
More file actions
38 lines (34 loc) · 1.12 KB
/
Best Time to Buy and Sell Stock III.h
File metadata and controls
38 lines (34 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
int maxProfit(vector<int> &prices) {
//go from left to right, calculate out maxprofit from 0 to i for each i
//go from right to left, calculate out maxprofit from i to end for each i
if(prices.size() == 0) return 0;
int ret = 0;
vector<int> maxProfit(prices.size(), 0);
//left to right
int buy = prices[0];
int maxsofar = 0;
for(int i = 0; i < prices.size(); ++i){
if(prices[i] < buy){
buy = prices[i];
}
if(prices[i]- buy > maxsofar){
maxsofar = prices[i] - buy;
}
maxProfit[i] = maxsofar;
}
//right to left
int sell = prices.back();
maxsofar = 0;
for(int i = prices.size()-1; i >= 0; --i){
if(maxProfit[i] + maxsofar > ret)
ret = maxProfit[i] + maxsofar;
if(prices[i] > sell)
sell = prices[i];
if(sell - prices[i] > maxsofar)
maxsofar = sell-prices[i];
}
return ret;
}
};