Tuesday, April 17, 2018

[2018-Interview] Best Time to Buy and Sell Stock

Original question: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

My answer: basically, I think the key logic is to always looking for the best result by index i, i.e. best profit by day "i". Once i reaches the end of array prices, it becomes the best result for all. Let's say the best profit by day "i" is maxProfit, then for day "i + 1", the maxProfit should be MAX(maxProfit, prices[i + 1] - minPrice). The minPrice is the min price by day "i"



class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        if (prices == null || prices.length < 2) {
            return maxProfit;
        }
        int minPrice = prices[0];
        for (int i = 1; i < prices.length ; i ++) {
            maxProfit = Math.max(maxProfit, prices[i] - minPrice);
            minPrice = Math.min(prices[i], minPrice);
        }
        return maxProfit;
    }
}

No comments:

Post a Comment