Tuesday, July 7, 2015

Best Time to Buy and Sell Stock | Leetcode

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: Go through each price, at the same time keeping the minimum price and maximum profit ever seen so far. By using the current price and this minimum price, we can calculate the maximum profit attainable.
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) return 0;
        int minPrice = prices[0];
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            maxProfit = Math.max(maxProfit, prices[i] - minPrice);
            minPrice = Math.min(minPrice, prices[i]);
        }
        return maxProfit;
    }
}

No comments: