leetocode213_House_Roubber2

I wrote a question earlier, how to rob the most on a street. This question is a succession of that question. The key point is that the street in front has become a ring.
Write the DP equation using java, dp[0] = nums[0], dp[1] = Math.max(nums[0], nums[1])
dp[i] = math.max(dp[i-2 ] + nums[i], dp[i - 1]),
I wrote a DPHelper directly, which can also solve a street

public static int robHelper (int[] nums, int lo, int hi) {
        int preRob = 0; //  simple explain
        int preNotRob = 0;
        int rob = 0;
        int notRob = 0;
        for (int j = lo; j <= hi; j++) {
            // what is the include and exclude
            rob = preNotRob + nums[j];
            notRob = Math.max(preRob, preNotRob);

            preRob = rob;
            preNotRob = notRob;

        }
        return Math.max(rob, notRob);

    }

Ring Street.

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

        return Math.max(robHelper(nums, 0, nums.length - 2), robHelper(nums, 1, nums.length - 1));
       // this is an extension of House Robber

    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484937&siteId=291194637