You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/3800-3899/3840.House Robber V/README_EN.md
+119-4Lines changed: 119 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -89,32 +89,147 @@ tags:
89
89
90
90
<!-- solution:start -->
91
91
92
-
### Solution 1
92
+
### Solution 1: Dynamic Programming
93
+
94
+
We define two variables $f$ and $g$, where $f$ represents the maximum amount when the current house is not robbed, and $g$ represents the maximum amount when the current house is robbed. Initially, $f = 0$ and $g = nums[0]$. The answer is $\max(f, g)$.
95
+
96
+
Next, we traverse starting from the second house:
97
+
98
+
- If the current house has the same color as the previous house, then $f$ is updated to $\max(f, g)$, and $g$ is updated to $f + nums[i]$.
99
+
- If the current house has a different color from the previous house, then $f$ is updated to $\max(f, g)$, and $g$ is updated to $\max(f, g) + nums[i]$.
100
+
101
+
Finally, return $\max(f, g)$.
102
+
103
+
The time complexity is $O(n)$, where $n$ is the number of houses. The space complexity is $O(1)$.
0 commit comments