-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path122.cpp
More file actions
49 lines (43 loc) · 1001 Bytes
/
122.cpp
File metadata and controls
49 lines (43 loc) · 1001 Bytes
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
/*
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
if(prices.size() <= 1)
return 0;
int valley = prices[0];
int peak = prices[0];
int i = 0;
int maxprofit=0;
while(i < prices.size()-1)
{
while(i < prices.size()-1 && prices[i] >= prices[i+1])
i++;
valley = prices[i];
while(i < prices.size()-1 && prices[i] <= prices[i+1])
i++;
peak = prices[i];
maxprofit += peak - valley;
}
return maxprofit;
}
};
*/
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
if(prices.size() <= 1)
return 0;
int maxprofit = 0;
for(int i=1; i < prices.size(); i++)
{
if(prices[i] > prices[i-1]) {
maxprofit += prices[i] - prices[i-1];
}
}
return maxprofit;
}
};