Friday, June 6, 2014

LeetCode Best Time to Buy and Sell Stock I

Need a variable to record the min value in the matrix

public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) return 0;
        int maxdiff = Integer.MIN_VALUE;
        int min = prices[0];
        for (int i=1; i<prices.length; i++) {
            //updating the max value
            if (prices[i] < min) {
                min = prices[i];
            }
            //updating the maxdiff
            if (maxdiff < prices[i] - min) {
                maxdiff = prices[i] - min;
            }
        }
        return maxdiff;
    }

No comments:

Post a Comment