Skip to content

Commit 4df5c73

Browse files
committed
House Robber: Optimized Dynamic Programming
1 parent d351aa2 commit 4df5c73

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

dynamic_programming/house_robber.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,41 @@ def rob(nums, i = nums.length - 1)
4747
nums = [2, 7, 9, 3, 1]
4848
puts rob(nums)
4949
# Output: 12
50+
51+
#
52+
# Approach 2: Optimized Dynamic Programming
53+
#
54+
55+
# Time Complexity
56+
#
57+
# Time Complexity: O(N) since we have a loop from N−2 and we use the precalculated
58+
# values of our dynamic programming table to calculate the current value in the table
59+
# which is a constant time operation.
60+
#
61+
# Space Complexity: O(1) since we are not using a table to store our values.
62+
# Simply using two variables will suffice for our calculations.
63+
#
64+
65+
def rob(nums)
66+
dp = Array.new(nums.size + 1)
67+
68+
(nums.size + 1).times do |i|
69+
dp[i] = if i == 0
70+
0
71+
elsif i == 1
72+
nums[0]
73+
else
74+
[dp[i - 2] + nums[i - 1], dp[i - 1]].max
75+
end
76+
end
77+
78+
dp[-1]
79+
end
80+
81+
nums = [1, 2, 3, 1]
82+
puts rob(nums)
83+
# Output: 4
84+
85+
nums = [2, 7, 9, 3, 1]
86+
puts rob(nums)
87+
# Output: 12

0 commit comments

Comments
 (0)