11/08/2012

Best Time to Buy and Sell Stock


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.

DP Solution:
public class Solution {
    public int maxProfit(int[] prices) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (prices.length <= 1) return 0;
        int min = prices[0];
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < min) min = prices[i];
            maxProfit = Math.max(prices[i] - min, maxProfit);
        }
        return maxProfit;
    }
}


Divide-n-Conquer:
public class Solution {
    private class MaxMin {
        public int max;
        public int min;
        public int profit;
        public MaxMin(int max, int min, int profit) {
            this.max = max;
            this.min = min;
            this.profit = profit;
        }
    }
    
    public int maxProfit(int[] prices) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if (prices.length <= 1) return 0;
        return _maxProfit(prices, 0, prices.length - 1).profit;
    }
    
    private MaxMin _maxProfit(int[] prices, int left, int right) {
        if (right - left <= 1) {
            MaxMin m = new MaxMin(
                Math.max(prices[right], prices[left]),
                Math.min(prices[right], prices[left]),
                Math.max(0, prices[right] - prices[left]));
            return m;
        }
        int mid = (right + left) / 2;
        MaxMin lm = _maxProfit(prices, left, mid);
        MaxMin rm = _maxProfit(prices, mid+1, right);
        int maxProfit = Math.max(Math.max(lm.profit, rm.profit), rm.max - lm.min);
        int min = Math.min(lm.min, rm.min);
        int max = Math.max(lm.max, rm.max);
        MaxMin m = lm;
        m.min = min;
        m.max = max;
        m.profit = maxProfit;
        return m;
    }
}

No comments:

Post a Comment