Skip to content

Instantly share code, notes, and snippets.

@themichaelyang
Created October 25, 2023 08:44
Show Gist options
  • Save themichaelyang/4167ac1c48eb08e657f546cc7ba05407 to your computer and use it in GitHub Desktop.
Save themichaelyang/4167ac1c48eb08e657f546cc7ba05407 to your computer and use it in GitHub Desktop.
def rob(nums)
rob_impl(nums, 0)
end
# https://nithinbekal.com/posts/ruby-memoization/
# https://stackoverflow.com/questions/35595047/how-to-generically-memoize-any-function-in-ruby
# We could use a Class instance to hold the memory
def memoize(method_name)
memory = {}
original = method(method_name)
# Needs to rebind the method name because of the recursive calls in the original method
define_method(method_name) do |*args|
if memory.include?(args)
memory[args]
else
memory[args] = original.call(*args)
end
end
end
memoize def rob_impl(nums, start_index)
if start_index >= nums.length - 1
nums[start_index] || 0
else
[
nums[start_index] + rob_impl(nums, start_index + 2),
rob_impl(nums, start_index + 1)
].max
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment