-
Notifications
You must be signed in to change notification settings - Fork 960
Expand file tree
/
Copy pathsolution.h
More file actions
23 lines (22 loc) · 721 Bytes
/
Copy pathsolution.h
File metadata and controls
23 lines (22 loc) · 721 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>
using std::vector;
#include <algorithm>
using std::min; using std::max;
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.empty()) return 0;
int low = prices.front(), high = prices.back(), ret = 0;
vector<int> history; history.reserve(prices.size());
for (auto today : prices) {
low = min(low, today);
ret = max(ret, today - low);
history.push_back(ret);
}
for (auto today = prices.crbegin(), past = history.crbegin(); today != prices.crend(); ++today, ++past) {
high = max(high, *today);
ret = max(ret, *past + high - *today);
}
return ret;
}
};