首页 > 其他 > 详细

Best Time to Buy and Sell Stock

时间:2014-11-08 20:47:58      阅读:229      评论:0      收藏:0      [点我收藏+]

这道题目号称是中等难度,但是我做的时候却觉得非常简单,好像应该算是easy的级别。

只是用了一个变量,时间复杂度是线性,从性能来说已经很不错了,时间在400ms左右,后来看了一眼讨论版,发现得票最多的家伙用了和我一样的方法,只不过那个家伙多定义了一个变量而已,不过定义之后也没用,可能他也忘记删除了。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1){
            return 0;
        }
        else{
            int profit = 0;
            int min=prices[0];
            for (int i = 0; i < prices.length; i++) {
                if (prices[i] < min) {
                    min = prices[i];
                } else {
                     if (prices[i] - min > profit) {
                        profit = prices[i] - min;
                      }
                }
            }
            return profit;
        }
    }
}

 

Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/bluedreamviwer/p/4083941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!