买卖股票的最佳时期

题目地址:地址


其实就是求后面的某个数减去前面某个数的最大值
那我们先来暴力法

class Solution {
    public int maxProfit(int[] prices) {
         int len =prices.length;
        if(len<=1){
            return 0;
        }
        int max =0;
        int oneMax =0;
        for(int i=0;i<len-1;i++){
           for(int j=i+1;j<len;j++){
               if(prices[j]>prices[i]){
                   oneMax=prices[j]-prices[i];
                   max =Math.max(max,oneMax);
               }
           }

        }
        return max;
    }
}
结果可想而知:
执行用时 : 815 ms, 在Best Time to Buy and Sell Stock的Java提交中击败了1.10% 的用户
内存消耗 : 38.8 MB, 在Best Time to Buy and Sell Stock的Java提交中击败了2.82% 的用户

能不能不用两个循环,一次循环就得到结果
思路: 在中间找到了下降的值A,让后面的值和它减,

  1. 如果后面的值B都大于A,结果就是取两个较大的B-A即maxProfit
  2. 如果后面突然有一个C,小于A,那么比较C-A的值和maxProfit较大的
  3. 如果C后面的值同样都大于C,那么就每次比较C-A的值,和maxProfit较大的
class Solution {
    public int maxProfit(int[] prices) {
   int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            int num = prices[i] - minPrice;
            if (num < 0) {
                minPrice = prices[i];
                continue;
            }

            maxProfit = Math.max(maxProfit, num);
        }
        return maxProfit;
    }
}
执行用时 : 3 ms, 在Best Time to Buy and Sell Stock的Java提交中击败了53.08% 的用户
内存消耗 : 37.9 MB, 在Best Time to Buy and Sell Stock的Java提交中击败了2.93% 的用户

题目二,地址

换了一个题目,其实就是求连续的增值的和,相对第一题有点简单

class Solution {
    public int maxProfit(int[] prices) {
           int len =prices.length;
        if(len<=1){
            return 0;
        }
        int total =0;
        int minOne =prices[0];
        for(int i=1;i<len;i++){
        //如果当前值大于前一个,不做任何处理,除非是最后一个
            if(prices[i]>=prices[i-1]){
                if(i==len-1){
                    return total+prices[i]-minOne;
                }
            }else {
            //如果当前值小于前面一个的值
            //1. 先把之前的加起来,再让最小的值是当前值
                total+=prices[i-1]-minOne;
                minOne =prices[i];

            }

        }
        return total;
    }
}
结果如下:
执行用时 : 2 ms, 在Best Time to Buy and Sell Stock II的Java提交中击败了75.22% 的用户
内存消耗 : 37.3 MB, 在Best Time to Buy and Sell Stock II的Java提交中击败了0.92% 的用户
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值