JunyiCode
4/3/2020 - 4:24 PM

121. Best Time to Buy and Sell Stock

/*
Note:
注意两行顺序
	    	res = Math.max(res, p - lowestBuyPrice);
	    	lowestBuyPrice = Math.min(lowestBuyPrice, p);

edge case: Descending order 
res initially is equal to 0
*/

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0)    return 0;
        int res = 0;
        int lowestBuyPrice = Integer.MAX_VALUE;
        
        for(int p : prices) {
	    	res = Math.max(res, p - lowestBuyPrice);
	    	lowestBuyPrice = Math.min(lowestBuyPrice, p);
        }
        
        return res;
    }
}
/*
edge case: Descending order 
*/

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