213. House Robber II

来源:互联网 发布:简谱演奏软件 编辑:程序博客网 时间:2024/04/29 11:19

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

public class Solution {    public int rob(int[] nums) {        if (nums == null || nums.length == 0) return 0;        if (nums.length == 1) return nums[0];        return Math.max(helper(nums, 0, nums.length-2), helper(nums, 1, nums.length-1));    }    public int helper(int[] nums, int start, int end) {        if (start == end) return nums[start];        if (start + 1 == end) return Math.max(nums[start], nums[end]);        int[] dp = new int[end-start+1];        dp[0] = nums[start];        dp[1] = Math.max(nums[start], nums[start+1]);        for (int i = start+2; i <= end; i++) {            dp[i-start] = Math.max(dp[i-1-start], nums[i]+dp[i-2-start]);        }        return dp[end-start];    }}
0 0
原创粉丝点击