Java DP solution O(1) space


  • 5
    B
    public int rob(int[] num) {
        if(num.length == 0) return 0;
        if(num.length == 1) return num[0];
        int[] value = new int[2];
        value[0] = num[0];
        value[1] = Math.max(num[0], num[1]);
        for(int i=2; i<num.length; i++){
            int temp = value[1];
            value[1] = Math.max(value[1], value[0]+num[i]);
            value[0] = temp;
        }
        return value[1];
    }

Log in to reply
 

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