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 a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 3:

Input: nums = [0]
Output: 0

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

Analyze

思考🤔: 将 4 2 3 5 拆成 4 2 3 与 2 3 5 两种情形。如此便将其转化为题目 198.House Robber

[0, n - 2] || [1, n - 1]
/ | \ \ / | ... \
[2, n - 2] [3, n - 2] [4, n - 2] ... [n - 2] [3, n - 1] [4, n - 1] ... [n - 1]
/
[4, n - 2]: 此时找到了重复子项
  • 状态的定义(即函数的定义): 考虑偷取 [m, n - 2] || [z, n - 1] 范围内的房子
  • 状态转移: f(0) = Math.max(v(0) + f(2), v(1) + f(3), v(2) + f(4), ..., v(n - 3) + f(n - 1), v(n - 2), v(n - 1))

递归:

/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
if (nums.length === 1) {
return nums[0]
}
const nums1 = nums.slice(0, nums.length - 1)
const nums2 = nums.slice(1, nums.length)
return Math.max(robPosition(nums1, 0, {}), robPosition(nums2, 0, {}))
}
var robPosition = function(nums, start, cache) {
let sum = 0
if (typeof nums[start] !== 'number') return 0
// the for loop can be optimized here.
for (let i = start; i < nums.length; i++) {
if (typeof cache[i] !== 'number') {
cache[i] = robPosition(nums, i + 2, cache)
}
sum = Math.max(sum, nums[i] + cache[i])
}
return sum
}

动态规划:

/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
if (nums.length === 0) return 0
if (nums.length === 1) {
return nums[0]
}
if (nums.length === 2) {
return Math.max(nums[0], nums[1])
}
const nums1 = nums.slice(0, nums.length - 1)
const nums2 = nums.slice(1, nums.length)
return Math.max(robPosition(nums1), robPosition(nums2))
}
var robPosition = (nums) => {
const lastDigit = nums[nums.length - 1]
const lastSecondDigit = nums[nums.length - 2]
const cache = {
0: lastDigit,
1: Math.max(lastSecondDigit, lastDigit)
}
let sum = Math.max(lastSecondDigit, lastDigit)
for (let i = 2; i < nums.length; i++) {
if (typeof cache[i] !== 'number') {
const point = nums.length - (i + 1)
cache[i] = Math.max(nums[point] + cache[i - 2], cache[i - 1])
}
sum = Math.max(sum, cache[i])
}
return sum
}