Java 1ms one pass solution


  • 0
    S
    public int maxProfit(int[] prices) {
            if (prices == null || prices.length == 0) return 0;
    	int min = prices[0], total = 0, currMax = 0;
    	for (int i = 1; i < prices.length; i++) {
    		if (prices[i]>min){
    			int profit =  prices[i]-min;
    			if (profit > currMax) {
    			currMax = profit;
    			continue;
    			}
    		}
    		total += currMax;
    		min = prices[i];
    		currMax = 0;
    	}
    	return total + currMax;
    }
    

Log in to reply
 

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