-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode_122_2.cpp
43 lines (42 loc) · 1022 Bytes
/
leetcode_122_2.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
#include "headl.h"
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), tr = 0, m = 0;
vector<int> ans(n, 0);
ans[0] = prices[0];
for (int i = 1; i < n; i++)
{
if (prices[i] > ans[i - 1])
{
if ((prices[i] - ans[i - 1]) > tr)
{
tr = prices[i] - ans[i - 1];
ans[i] = ans[i - 1];
}
else
{
ans[i] = prices[i];
m += tr;
tr = 0;
}
}
else
{
ans[i] = prices[i];
if(tr) m += tr;
tr = 0;
}
}
if(tr) m += tr;
return m;
}
};
int main()
{
freopen("test_in.txt", "r", stdin);
freopen("test_out.txt", "w", stdout);
Solution* a = new Solution();
vector<int> b = { 2,1,2,0,1 };
a->maxProfit(b);
}