Friday, March 28, 2014

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i. 
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution1: straight forward, buy at the low price before it goes up and sell at the high price before it goes down.
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2)
            return 0;
        if (prices.length == 2)
            return prices[0] > prices[1] ? 0 : prices[1] - prices[0];
        
        int low = 0;  
        int high = 0;
        int ans = 0;
        boolean hold = false;
        for (int i = 0; i < prices.length - 1; i++) {
            if (!hold && prices[i] < prices[i+1]) {
                hold = true;
                low = prices[i];
                continue;
            } 
            if (hold && prices[i] > prices[i+1]) {
                hold = false;
                high = prices[i];
                ans += high - low;
            }
        }
        
        if (hold)
            ans += prices[prices.length-1] - low;
        return ans;
    }
}
Solution2: more mathematical way, add every increment
public class Solution {
    public int maxProfit(int[] prices) {
        int ans = 0;
        for (int i = 0; i < prices.length - 1; i++)
            ans += (prices[i+1] > prices[i] ? prices[i+1] - prices[i] : 0);
       
        return ans;
    }
}

No comments:

Post a Comment