Skip to content

Commit cc074b4

Browse files
committed
Add solution #213
1 parent d2066c1 commit cc074b4

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@
8989
198|[House Robber](./0198-house-robber.js)|Medium|
9090
203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy|
9191
206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy|
92+
213|[House Robber II](./0213-house-robber-ii.js)|Medium|
9293
214|[Shortest Palindrome](./0214-shortest-palindrome.js)|Hard|
9394
217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy|
9495
219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy|

solutions/0213-house-robber-ii.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 213. House Robber II
3+
* https://leetcode.com/problems/house-robber-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are a professional robber planning to rob houses along a street. Each house has a certain
7+
* amount of money stashed. All houses at this place are arranged in a circle. That means the
8+
* first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system
9+
* connected, and it will automatically contact the police if two adjacent houses were broken into
10+
* on the same night.
11+
*
12+
* Given an integer array nums representing the amount of money of each house, return the maximum
13+
* amount of money you can rob tonight without alerting the police.
14+
*/
15+
16+
/**
17+
* @param {number[]} nums
18+
* @return {number}
19+
*/
20+
var rob = function(nums) {
21+
if (nums.length === 1) {
22+
return nums[0];
23+
}
24+
25+
return Math.max(
26+
handlePermutation(nums, 0, nums.length - 1),
27+
handlePermutation(nums, 1, nums.length)
28+
);
29+
};
30+
31+
function handlePermutation(nums, start, end) {
32+
let previous = 0, current = 0;
33+
34+
for (let i = start; i < end; i++) {
35+
const temp = previous;
36+
previous = current;
37+
current = Math.max(temp + nums[i], previous);
38+
}
39+
40+
return Math.max(current, previous);
41+
}

0 commit comments

Comments
 (0)