Java clean short solution DP


  • 18
    J
    public class Solution {
    public int rob(int[] nums) {
    	return Math.max(rob(nums, 0, nums.length-2), rob(nums, 1, nums.length-1));
    }
    
    public int rob(int[] nums, int lo, int hi) {
        int preRob = 0, preNotRob = 0, rob = 0, notRob = 0;
        for (int i = lo; i <= hi; i++) {
          	rob = preNotRob + nums[i];
        	notRob = Math.max(preRob, preNotRob);
        	
        	preNotRob = notRob;
        	preRob = rob;
        }
        return Math.max(rob, notRob);
    }
    

    }


  • 0
    M

    Hahaha, I had exactly the same solution for the robber 1 problem. I can't believe your modification to the circle robber is so elegant! gj


  • 1
    H

    I think your code can't pass current tests, since they add some edge cases. Here is my update for the main function. The other function doesn't need to change.

        public int rob(int[] nums) {
            if (nums.length==1) return nums[0];
            return Math.max(rob(nums, 0, nums.length-2), rob(nums, 1, nums.length-1));
        }
    

Log in to reply
 

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