Tuesday, February 26, 2013

[LeetCode] Best Time to Buy and Sell Stock I

Thought:
Just Keep track of the min price and the local max profit.

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

No comments:

Post a Comment