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.
這題和 198. House Robber (Medium) 差不多但不同的點在於現在房子變成循環的,也就是說如果偷了第一間那麼最後一間也不能偷,同理最後一間偷了則第一間不能偷。
因為偷了第一間(從第一間開始)就不能偷最後一間,所以將最後一間移除掉並和 198. House Robber (Medium) 一樣建立 移除掉最後一間房子
的 dp array
接著建立第二個 dp 是從略過第一間,如果略過第一間就可以偷到最後一間(從第二間開始),所以移除掉第一間並和198. House Robber (Medium) 一樣建立 移除掉第一間房子
的 dp array
2 (nums = [2,7])
已經算過並放進 dp 裡面了2 (nums = [2,7])
已經算過並放進 dp 裡了3 (nums = [2,7,9])
中算過並放進 dp 中了3 (nums = [7,9])
已經算過並放進 dp 裡面了nums = [7,9]
在 3
已經算過並放進 skipFirstHouseDp 中了4 (nums = [7,9,3])
已經算過並放進 dp 裡面了比較 skipLastHouseDp
和 skipFirstHouseDp
中最大值便是解答。
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
if (nums.length === 1) return nums[0];
if (nums.length === 2) return Math.max(nums[0], nums[1]);
const skipLastHouse = [];
skipLastHouse[0] = nums[0];
skipLastHouse[1] = Math.max(nums[0], nums[1]);
for(let i = 2; i < nums.length - 1; i++) {
skipLastHouse[i] = Math.max(nums[i] + skipLastHouse[i - 2], skipLastHouse[i - 1]);
}
const skipFirstHouse = [];
skipFirstHouse[1] = nums[1];
skipFirstHouse[2] = Math.max(nums[1], nums[2]);
for(let i = 3; i < nums.length; i++) {
skipFirstHouse[i] = Math.max(nums[i] + skipFirstHouse[i - 2], skipFirstHouse[i - 1]);
}
return Math.max(skipLastHouse[skipLastHouse.length - 1], skipFirstHouse[skipFirstHouse.length - 1]);
};