forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
198_House_Robber
59 lines (49 loc) · 1.19 KB
/
198_House_Robber
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Leetcode 198: House Robber
Detailed video explanation: https://youtu.be/jzpsHKJy00c
=========================================
C++:
----
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 0) return 0;
if(n == 1) return nums[0];
int v1 = nums[0], v2 = max(v1, nums[1]);
for(int i = 2; i < n; ++i){
int tmp = v2;
v2 = max(v2, v1 + nums[i]);
v1 = tmp;
}
return v2;
}
};
Java:
----
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if(n == 0) return 0;
if(n == 1) return nums[0];
int v1 = nums[0], v2 = Math.max(v1, nums[1]);
for(int i = 2; i < n; ++i){
int tmp = v2;
v2 = Math.max(v2, v1 + nums[i]);
v1 = tmp;
}
return v2;
}
}
Python3:
-------
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 0: return 0
if n == 1: return nums[0]
v1, v2 = nums[0], max(nums[0], nums[1])
for i in range(2, n):
tmp = v2;
v2 = max(v2, v1 + nums[i])
v1 = tmp
return v2