-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimeToBuyAndSellStockIII.cpp
More file actions
59 lines (53 loc) · 1.39 KB
/
BestTimeToBuyAndSellStockIII.cpp
File metadata and controls
59 lines (53 loc) · 1.39 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices, vector<pair<int, int> > &waves, int lo, int hi){
if(lo > hi)
return 0;
int min = prices[waves[lo].first];
int max_profit = 0;
for(int i=lo; i<=hi; i++){
if(prices[waves[i].first] < min)
min = prices[waves[i].first];
if(prices[waves[i].second] - min > max_profit)
max_profit = prices[waves[i].second] - min;
}
return max_profit;
}
int maxProfit(vector<int>& prices) {
vector<pair<int, int> > waves;
for(int i=0; i<prices.size(); i++){
int j = i+1;
for(; j<prices.size(); j++){
if(prices[j] < prices[j-1])
break;
}
j = j-1;
if(j>i)
waves.push_back(make_pair(i, j));
i = j;
}
for(auto &i : waves){
cout << i.first << " " << i.second << endl;
}
int max_profit = 0;
for(int i=0; i<waves.size(); i++){
int left_profit = maxProfit(prices, waves, 0, i);
int right_profit = maxProfit(prices, waves, i+1, waves.size()-1);
cout << left_profit << " " << right_profit << endl;
if(left_profit+right_profit > max_profit)
max_profit = left_profit+right_profit;
}
return max_profit;
}
};
int main(int argc, char *argv[]) {
vector<int> prices = {9,9,0,3,0,7,7,7,4,1,5,0,1,7};
Solution sol;
cout << sol.maxProfit(prices) << endl;
return 0;
}