导航

Best Time to Buy and Sell Stock

Posted on 2014-11-08 20:13  八竿子打不着  阅读(143)  评论(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;
        }
    }
}