Wednesday, September 24, 2014

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.
Understand the problem:
The problem means that you can buy and stock at some day and sell it another day, and make the profit maximal. If you cannot make a profit, you can also not buy at all. Note that you are able to buy/sell at most once. 

The basic idea for this question is to maintain the maximal profit, which is the difference of sell and buy prices. One way is to maintain a minimum buy price and compare the current price with that, compute the profit and update the maximal profit. 

Code (Java):
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        
        int minIn = prices[0];
        int maxProfit = 0;
        
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] - minIn > maxProfit) {
                maxProfit = prices[i] - minIn;
            }
            
            if (prices[i] < minIn) {
                minIn = prices[i];
            }
        }
        
        return maxProfit;
    }
}

Summary:
The take-away message for such kind of application problems is to understand the problem first, then generalize a "model" that can solve the problem. 

No comments:

Post a Comment