阿亮的算法之路——121买股票的最佳时机

题目描述

买股票的最佳时机这题被归纳为了动规,但好像往动规的方向思考,没有思路,索性用原始一点的方法

首次提交

代码

    public static int maxProfit(int[] prices)
    {
        int len ;
        if (prices == null || (len = prices.length) == 0) { return 0; }
        int min = prices[0];
        int diff = 0;
        for (int i = 1; i < len; i++)
        {
            diff = diff > prices[i] - min? diff: prices[i] - min;
            if (min > prices[i]) { min = prices[i]; }
        }
        return diff;
    }

提交结果
提交结果1
看起来还不错的样子

官方题解

代码

    public int maxProfit(int[] prices)
     {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) 
        {
            if (prices[i] < minprice)
                minprice = prices[i];
            else if (prices[i] - minprice > maxprofit)
                maxprofit = prices[i] - minprice;
        }
        return maxprofit;
    }

提交结果
提交结果1效果好像差不多,可能对于太简单的题,算法对于性能的优化效果就没那么大

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值