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;
}
};
本文介绍了一个C++实现的算法,该算法用于计算给定股价数组中通过多次买卖所能获得的最大利润。通过跟踪股价的波动趋势,算法能够识别买入和卖出的最佳时机。
416

被折叠的 条评论
为什么被折叠?



