My Java 1ms Solution


  • 0
    N
    public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<2) return 0;
        int buy0 = -prices[0];
        int buy1 = Math.max(-prices[0], -prices[1]);
        int sell0 = 0;
        int sell1 = Math.max(0,prices[1]-prices[0]);
        int buy2=0, sell2=sell1;
        for(int i=2;i<prices.length;i++){
            buy2 = Math.max(buy1, sell0-prices[i]);
            sell2 = Math.max(buy1+prices[i], sell1);
            buy1 = buy2;
            sell0 = sell1;
            sell1 = sell2;
        }
        return sell2;
    }

Log in to reply
 

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