2014年11月30日星期日

[Leetcode] Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Keep the minimum value we could obtain to now, find the difference between the current value with the minimum, update the maximum if necessary.


    public int maxProfit(int[] prices) {
        int res = 0;
        int n = prices.length;
        if(n == 0)
            return 0;
        int mi = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++) {
            mi = Math.min(mi, prices[i]);
            res = Math.max(res, prices[i] - mi);
        }
        return res;
    }

没有评论:

发表评论