-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
67 lines (63 loc) · 1.88 KB
/
Solution.cpp
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
60
61
62
63
64
65
66
67
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxProfit_increasing_stack(vector<int>& prices) {
if (prices.size() <= 1) return 0;
vector<int > stk {prices[0]};
// stk is increasing, not only non-decreasing
int res = 0;
for (int i=1; i<prices.size(); ) {
if (prices[i] <= stk.back()) {
if (stk.size() == 1) stk.back() = prices[i++];
else {
int diff = stk.back() - stk.front();
res = diff > res ? diff : res;
stk.pop_back();
}
} else {
stk.push_back(prices[i++]);
}
}
if (stk.size() >= 2) {
int diff = stk.back() - stk.front();
res = diff > res ? diff : res;
}
return res;
}
// changes to max consecutive sum problem , the same
int maxProfit_max_consecutive_sum(vector<int>& prices) {
if (prices.size() <= 1) return 0;
vector < int > r (prices.size());
for (int i=1; i<prices.size(); i++) {
r[i] = prices[i] - prices[i-1];
}
int max = 0, sum = 0;
for (int i=0; i<prices.size(); i++) {
sum += r[i];
if (sum > max) max = sum;
if (sum < 0 ) sum = 0;
}
return max;
}
// reasonalbe : easy to reasion about
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
int minprice = 1 << 30, maxprofit = 0;
for (auto i : prices) {
minprice = i < minprice ? i : minprice;
maxprofit = i - minprice > maxprofit ? i - minprice : maxprofit;
}
return maxprofit;
}
};
int main() {
Solution s;
vector<int> v {7,1,5,3,6,4};
s.maxProfit(v);
return 0;
}