213 House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.

Example:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.

解釋下題目:

198類似,加了一個頭尾不能同時搶的條件

1. 小聰明

實際耗時:0ms

public int rob(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    } else if (nums.length == 1) {
        return nums[0];
    }
    // ensure that the length of array is 2 or more
    return Math.max(robHelp(Arrays.copyOfRange(nums, 1, nums.length)), robHelp(Arrays.copyOfRange(nums, 0, nums.length - 1)));
}

public int robHelp(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    if (nums.length == 1) {
        return nums[0];
    }
    int[][] dp = new int[nums.length][2];
    //init
    dp[0][0] = 0;
    dp[0][1] = nums[0];
    for (int i = 1; i < nums.length; i++) {
        // if robber do not rob the house
        dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
        // robber rob the house
        dp[i][1] = dp[i - 1][0] + nums[i];
    }
    return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]);
}

??其實就是調(diào)用了198那題的解法,然后既然加了頭尾不能同時搶,那我分兩次唄,一次是[0,n-1],另外一次是[1,n],然后取兩者中比較大的那個就好了。

時間復(fù)雜度O(n)
空間復(fù)雜度O(n)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容