-
Notifications
You must be signed in to change notification settings - Fork 0
/
BestTimetoBuyandSellStockII.cpp
54 lines (45 loc) · 1.11 KB
/
BestTimetoBuyandSellStockII.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
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
/*int sum=0;
int cur=0;
for(int i=0;i<prices.size();i++){
if(i==0) cur=prices[i];
else{
if(prices[i]>cur){
sum+=prices[i]-cur;
}
cur=prices[i];
}
}
return sum;*/
int i=0;
int valley=prices[0];
int peak=prices[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;
}
};
int main(){
int n;
cin>>n;
vector<int> prices;
for(int i=0;i<n;i++){
int num;
cin>>num;
prices.push_back(num);
}
Solution *solution=new Solution();
cout<<solution->maxProfit(prices);
return 0;
}