-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path122_max_profit.cc
50 lines (46 loc) · 1.32 KB
/
122_max_profit.cc
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
#include <vector>
using namespace::std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), profit = 0;
if (n == 0)
return 0;
int pre_hold = -prices[0], pre_unhold = 0;
for (int i = 1; i < n; ++i) {
int hold = max(pre_hold, pre_unhold - prices[i]);
int unhold = max(pre_hold + prices[i], pre_unhold);
pre_hold = hold;
pre_unhold = unhold;
}
return pre_unhold;
}
int maxProfit2(vector<int>& prices)
{
int n = prices.size(), profit = 0;
if (n == 0)
return 0;
int last = prices[0];
for (int i = 1; i < n; ++i) {
if (prices[i] > last)
profit += prices[i] - last;
last = prices[i];
}
return profit;
}
int maxProfit3(vector<int>& prices) {
int n = prices.size(), profit = 0;
if (n == 0)
return 0;
int minval = prices[0], maxval = prices[0];
for (int i = 1; i < n; ++i) {
if (prices[i] > maxval)
maxval = prices[i];
if (prices[i] < maxval || i == n - 1) {
profit += maxval - minval;
maxval = minval = prices[i];
}
}
return profit;
}
};