Saturday, January 10, 2015

LeetCode 121: 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.
public class Solution {
    public int maxProfit(int[] prices) {
        // Traverse the array to compare current price with minimum price before the current price.
        int n = prices.length;
        
        if (n <= 1)
            return 0;
        
        // Minimum price before current price    
        int minBfCur = prices[0];
        int maxProfit = 0;
        
        for (int i = 0; i < n; i++)
        {
            maxProfit = Math.max(maxProfit, prices[i]-minBfCur);
            minBfCur = Math.min(minBfCur, prices[i]);
        }
        
        return maxProfit;
    }
}

No comments:

Post a Comment