Wednesday, February 25, 2015

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.
Solution
一次扫描完成。只需要找到最大增长即可。
从前往后,用当前价格减去此前最低价格,就是在当前点卖出股票能获得的最高利润。
扫描的过程中更新最大利润和最低价格就行了。
time complexity is O(n). constant space.
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1)
            return 0;
            
        int minprice = prices[0];
        int result = 0;
        
        for(int i = 1; i < prices.length; i++) {
            minprice = Math.min(prices[i], minprice);
            int diff = prices[i] - minprice;
            if(result < diff)
                result = diff;
        }
        return result;
    }
}

No comments:

Post a Comment