2ms Java DP solution, easy understand


  • 1
    C
        public int maxProfit(int[] prices){
        if(null == prices || 1 >= prices.length) return 0;
        
        int last = 0, current = 0, maxProfit = prices[1] - prices[0];
        
        //i means sell in the ith day
        for(int i = 1; i < prices.length; i ++){
        	current = last > 0? last + prices[i] - prices[i - 1] : prices[i] - prices[i - 1];
        	maxProfit = current > maxProfit? current : maxProfit;
        	last = current;
        }
        
        return maxProfit >= 0? maxProfit : 0;//0 means do not sell
    }

Log in to reply
 

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