Code Explanation:
1. Function Definition
def rob(nums):
This defines a function called rob that takes a single parameter nums, which is a list of integers.
Each integer in nums represents the amount of money in a house.
The goal is to compute the maximum amount of money that can be robbed without robbing two adjacent houses.
2. Handle Empty Input
if not nums:
return 0
If the list nums is empty (i.e., there are no houses to rob), the function returns 0.
not nums is True when the list is empty.
3. Initialize State Variables
a, b = 0, 0
These two variables represent the maximum money that can be robbed:
a: maximum money robbed up to the house before the previous one (i.e., i-2)
b: maximum money robbed up to the previous house (i.e., i-1)
Both are initially 0 since no money has been robbed yet.
4. Iterate Through Each House
for n in nums:
This loop goes through each house (each value n in nums).
n represents the amount of money in the current house.
5. Update State Variables
a, b = b, max(b, a + n)
This is the key logic of the algorithm.
Temporarily:
a becomes the previous value of b (previous house's max loot).
b becomes the max of:
b (not robbing current house, keep max so far)
a + n (rob current house, so we add its value to max loot up to i-2)
This ensures no two adjacent houses are robbed.
6. Return Final Result
return b
After processing all houses, b holds the maximum money that can be robbed without violating the "no two adjacent houses" rule.
7. Function Call and Output
print(rob([2, 7, 9, 3, 1]))
Calls the rob function with [2, 7, 9, 3, 1] as input.
Expected Output: 12
Rob house 1 (2), skip house 2, rob house 3 (9), skip house 4, rob house 5 (1) → 2 + 9 + 1 = 12
Output:
12
.png)

0 Comments:
Post a Comment