-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path122. Best Time to Buy and Sell Stock II
60 lines (53 loc) · 1.14 KB
/
122. Best Time to Buy and Sell Stock II
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
class Solution {
public:
int maxProfit(vector<int>& prices) {
prices.push_back(0);
int n= prices.size();
int b=prices[0], s=0;
int ans = 0, max=0;
for(int i=1; i<n; i++)
{
if(b>prices[i])
{
b = prices[i];
}
else if(s < prices[i] )
{
s = prices[i];
}
if(s>0 && prices[i]>prices[i+1])
{
ans+=s-b;
s=0;
b=prices[i];
}
}
return ans;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n= prices.size();
int b=prices[0], s=0;
int ans = 0, max=0;
for(int i=1; i<n; i++)
{
if(b>prices[i])
{
b = prices[i];
}
else if(s < prices[i] )
{
s = prices[i];
}
if(s>0)
{
ans+=s-b;
s=0;
b=prices[i];
}
}
return ans;
}
};