File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 89
89
198|[ House Robber] ( ./0198-house-robber.js ) |Medium|
90
90
203|[ Remove Linked List Elements] ( ./0203-remove-linked-list-elements.js ) |Easy|
91
91
206|[ Reverse Linked List] ( ./0206-reverse-linked-list.js ) |Easy|
92
+ 213|[ House Robber II] ( ./0213-house-robber-ii.js ) |Medium|
92
93
214|[ Shortest Palindrome] ( ./0214-shortest-palindrome.js ) |Hard|
93
94
217|[ Contains Duplicate] ( ./0217-contains-duplicate.js ) |Easy|
94
95
219|[ Contains Duplicate II] ( ./0219-contains-duplicate-ii.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments