Open Tcdian opened 3 years ago
function rob(nums: number[]): number {
const len = nums.length;
if (len < 3) {
return dpRob(nums);
}
return Math.max(dpRob(nums.slice(0, nums.length - 1)), dpRob(nums.slice(1)));
function dpRob(nums: number[]): number {
const len = nums.length;
if (len === 0) {
return 0;
}
let dp = new Array(len);
for (let i = 0; i < len; i++) {
if (i === 0) {
dp[i] = nums[i];
} else if (i === 1) {
dp[i] = Math.max(nums[i], dp[i - 1]);
} else {
dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]);
}
}
return dp[len - 1];
}
};
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 a list of non-negative integers
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
Example 2
Example 3
Constraints
1 <= nums.length <= 100
0 <= nums[i] <= 1000