easiest java solution,only consider whether sell or not on day i


  • 0
    K
    public int maxProfit(int[] prices) {
            int len= prices.length;
            if(len<2)
                return 0;
            int [] dp = new int[len];
            dp[1]=Math.max(0,prices[1]-prices[0]);
            int localmax=0-Math.min(prices[0],prices[1]);
            for(int i=2;i<len;i++){
                dp[i]=Math.max(dp[i-1],prices[i]+localmax);
                localmax=Math.max(localmax,dp[i-2]-prices[i]);
            }
            return dp[len-1];
        }
    

Log in to reply
 

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