No.121
class Solution {
public int maxProfit(int[] prices) {
int len=prices.length;
if(len==0) return 0;
int minPrices=prices[0];
int maxPro=0;
for(int i=1;i<len;++i){
if(prices[i]<minPrices)
minPrices=prices[i];
else
maxPro=(prices[i]-minPrices>maxPro)?prices[i]-minPrices:maxPro;
}
return maxPro;
}
}
//评论看见的值得参考的C语言代码
// int maxProfit(int* prices, int pricesSize) {
// int max = 0,realmax = 0;
// for(int i = 1; i < pricesSize; i++) {
// max += prices[i] - prices[i-1]; 重点是这一行代码 max<0说明这一部分的总体趋势还是下降的
// if(max < 0)
// max = 0;
// if(max > realmax)
// realmax = max;
// }
// return realmax;
// }
No.122
class Solution { //巧妙之处在于从起点开始 先找谷底再找峰顶,没有谷底则必有峰顶,
public int maxProfit(int[] prices) {
int len=prices.length;
if(len<=1)
return 0;
int valley=prices[0];
int peak=prices[0];
int max=0;
int i=0;
while(i<len-1){
while(i<len-1&&prices[i]>=prices[i+1]){
++i;
}
valley=prices[i]; //这里巧妙的把这两行赋值代码放在while外面,一是节省了运行时间,
//更重要的是保证了峰顶至少等于谷底。避免了在没有新峰顶出现的时候(例如一直下降或者
// 最后一段是下降) 所造成的错误结果
while(i<len-1&&prices[i]<=prices[i+1]){
++i;
}
peak=prices[i];
max+=peak-valley;
}
return max;
}
}