213. House Robber II
June 24, 2025
04:32 AM
No headings found
Loading content...
No headings found
Problem
Điều kiện các ngôi nhà được sắp xếp thành một vòng tròn
Approach
Time and space complexity
Solution
curr = i - 1
1function rob(nums: number[]): number {
2 if(nums.length === 0) return 0;
3 if(nums.length === 1) return nums[0];
4
5 function robLinear(nums: number[]): number {
6 let prev = 0;
7 let curr = 0;
8
9 for(const num of nums) {
10 const temp = curr;
11 curr = Math.max(curr, prev + num);
12 prev = temp;
13 }
14
15 return curr;
16 }
17
18 const case1 = robLinear(nums.slice(0, nums.length - 1));
19 const case2 = robLinear(nums.slice(1));
20
21 return Math.max(case1, case2);
22};