File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed
Algorithms/213.House-Robber-II Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int rob (vector<int >& nums) {
4
+ if (nums.size () == 0 )
5
+ return 0 ;
6
+ if (nums.size () == 1 )
7
+ return nums[0 ];
8
+ if (nums.size () == 2 )
9
+ return max (nums[0 ], nums[1 ]);
10
+
11
+ vector<int > dp (nums.size (),0 );
12
+ dp[0 ] = nums[0 ];
13
+ dp[1 ] = max (nums[0 ],nums[1 ]);
14
+
15
+ for (int i=2 ;i<nums.size ()-1 ;i++){
16
+ dp[i] = max (dp[i-2 ]+nums[i],dp[i-1 ]);
17
+ }
18
+
19
+ int max1 = dp[nums.size ()-2 ];
20
+
21
+ dp[1 ] = nums[1 ];
22
+ dp[2 ] = max (nums[1 ],nums[2 ]);
23
+
24
+ for (int i=3 ;i<nums.size ();i++){
25
+ dp[i] = max (dp[i-2 ]+nums[i],dp[i-1 ]);
26
+ }
27
+
28
+ int max2 = dp[nums.size ()-1 ];
29
+
30
+ return max (max1, max2);
31
+
32
+ }
33
+ };
Original file line number Diff line number Diff line change 379
379
380
380
[ 211.Add-and-Search-Word---Data-structure-design] ( Algorithms/211.Add-and-Search-Word---Data-structure-design/solution.cpp )
381
381
382
+ [ 213.House-Robber-II] ( Algorithms/213.House-Robber-II/solution.cpp )
383
+
382
384
[ 214.Shortest-Palindrome] ( Algorithms/214.Shortest-Palindrome/solution.cpp )
383
385
384
386
[ 215.Kth-Largest-Element-in-an-Array] ( Algorithms/215.Kth-Largest-Element-in-an-Array/solution.cpp )
You can’t perform that action at this time.
0 commit comments