A DP Solution in Java - O(n)


  • 2
    H
    public int maxProfit(int[] prices) {
    	if (prices == null || prices.length == 0) {
    		return 0;
    	}
    	int maxProfit = prices[0] - prices[0];
    	int minPrice = prices[0];
    	for (int i = 0; i < prices.length; i ++) {
    		minPrice = prices[i] < minPrice ? prices[i] : minPrice;
    		maxProfit = (prices[i] - minPrice) > maxProfit ? (prices[i] - minPrice) : maxProfit;
    	}
    	return maxProfit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.