-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode第122题.cpp
More file actions
36 lines (36 loc) · 943 Bytes
/
Leetcode第122题.cpp
File metadata and controls
36 lines (36 loc) · 943 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
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1){
return 0;
}
bool isIncreasing=true;
for(int i=0;i<prices.size()-1;++i){
if(prices[i+1]<prices[i]){
isIncreasing=false;
break;
}
}
if(isIncreasing==true){
return prices[prices.size()-1]-prices[0];
}
int res=0,temp=0;
int cost=prices[0],profit=prices[0];
for(int i=0;i<prices.size();++i){
profit=prices[i];
if(profit-cost<0){
cost=profit;
}
if(profit-cost<temp){
res+=temp;
temp=0;
cost=profit;
}
if(i==prices.size()-1&&profit-cost>=temp){
res+=profit-cost;
}
temp=profit-cost;
}
return res;
}
};