Simple Java Solution using DP


  • 1
    Z
    public class Solution {
        public int rob(int[] nums) {
            int len = nums.length;
            if (len == 0)
                return 0;
            else if (len == 1)
                return nums[0];
            else {
                int[] value = new int[len+1];
                value[0] = 0;  
                value[1] = nums[0];
                for (int i = 2; i < len+1; i++) {
                    value[i] = Math.max(value[i-2]+nums[i-1], value[i-1]);
                }
                return value[len];
            }
        }
    }

Log in to reply
 

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