class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxPos = prices.size() - 1;
if(maxPos < 0 ) return 0;
int maxTemp = 0 ;//短线的上升沿最大值
int minTemp = 0;//短线的上升沿的最小值
bool climbing = prices[1]-prices[0]>=0 ? true : false ;
if(climbing){
minTemp = prices[0];
maxTemp = prices[1];
}else{
minTemp = prices[1];
maxTemp = prices[1];
}
int total = 0;
int i=2;
for(;i<=maxPos;i++){
if(prices[i]-prices[i-1]>=0){
if(climbing){
maxTemp = prices[i];
}else{
minTemp = prices[i-1];
maxTemp = prices[i];
climbing = true;
}
}
if(prices[i]-prices[i-1]<0){
if(climbing){
total += prices[i-1] - minTemp;
climbing = false;
minTemp = prices[i];
maxTemp = prices[i];
}else{
minTemp = prices[i];
maxTemp = prices[i];
}
}
}
if(climbing && i>maxPos){
total += prices[i-1] - minTemp;
}
return total;
}
};
public:
int maxProfit(vector<int>& prices) {
int maxPos = prices.size() - 1;
if(maxPos < 0 ) return 0;
int maxTemp = 0 ;//短线的上升沿最大值
int minTemp = 0;//短线的上升沿的最小值
bool climbing = prices[1]-prices[0]>=0 ? true : false ;
if(climbing){
minTemp = prices[0];
maxTemp = prices[1];
}else{
minTemp = prices[1];
maxTemp = prices[1];
}
int total = 0;
int i=2;
for(;i<=maxPos;i++){
if(prices[i]-prices[i-1]>=0){
if(climbing){
maxTemp = prices[i];
}else{
minTemp = prices[i-1];
maxTemp = prices[i];
climbing = true;
}
}
if(prices[i]-prices[i-1]<0){
if(climbing){
total += prices[i-1] - minTemp;
climbing = false;
minTemp = prices[i];
maxTemp = prices[i];
}else{
minTemp = prices[i];
maxTemp = prices[i];
}
}
}
if(climbing && i>maxPos){
total += prices[i-1] - minTemp;
}
return total;
}
};