My Java solution


  • 2
    K
    public int rob2(int[] nums) {
    	if (nums.length == 0)
    		return 0;
    	int[] arr = new int[nums.length << 1 + 1];
    	arr[0] = 0;
    	arr[1] = nums[0];
    	if (nums.length == 1)
    		return arr[1];
    	for (int i = 1; i < nums.length << 1; i++) {
    		arr[i + 1] = Math.max(arr[i], arr[i - 1] + nums[i % nums.length]);
    	}
    	return arr[nums.length << 1] - arr[nums.length];
    }

  • 0
    D

    Could you explain why this is correct?


  • 0
    K
    public int rob2(int[] nums) {
    	if (nums.length == 0) // the length is 0, he will rob nothing
    		return 0;
    	int[] arr = new int[nums.length << 1 + 1];// "<<" equals multiplied by 2
    	arr[0] = 0;
    	arr[1] = nums[0];
    	if (nums.length == 1)
    		return arr[1];
    	for (int i = 1; i < nums.length << 1; i++) { // this is a dynamic programming method
    		arr[i + 1] = Math.max(arr[i], arr[i - 1] + nums[i % nums.length]);
    	}
    	return arr[nums.length << 1] - arr[nums.length];// "arr[nums.length << 1]" and "arr[nums.length]" calculates in a circle , so the difference between them is the result
    }

Log in to reply
 

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