leetcode No.121,122买卖股票的最佳时机

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;
         
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值