-
Couldn't load subscription status.
- Fork 0
Solved Arai60/198. House Robber #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| total_robbed_at_house = nums[:2] | ||
| total_robbed_at_house.append(nums[0] + nums[2]) | ||
| for i in range(3, len(nums)): | ||
| total_robbed_at_house.append(max(total_robbed_at_house[i-3:i-1]) + nums[i]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
max() に渡す前にスライスを使い、部分 list のコピーを作っている点が、処理が定数倍重くなりそうだなと感じました。ただ、 Python のようにもともと重い言語で定数倍の速度差を気にするのも微妙だと思いました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
そうですね。少し気になりましたが、分けて書くほどでもないのかなと思ってしまいました
| ```python | ||
| class Solution: | ||
| def rob(self, nums: List[int]) -> int: | ||
| max_rob = [nums[0]] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
最後 2 個のみ保持すれば十分で、空間計算量 O(1) になります。
| max_rob = [nums[0]] | ||
| max_rob.append(max(nums[:2])) | ||
| for i in range(2, len(nums)): | ||
| max_rob.append(max(max_rob[-2] + nums[i], max_rob[-1])) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
space O(1) で解けますよというのもありますね。
space O(N) で解くのであれば append していってもいいんですが、DP に使う配列は事前に len(nums) で定義しておいて、max_rob[i] = ...max_rob[i -1]...max_rob[i - 2] のような感じでアクセスしたほうが、それまでの要素との関係性で max_rob[i] を定義していることがわかりやすいかなと感じます。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
確かに先に作ってしまう方がよく見る気がしますね。C言語とかでリスト長を指定する流れからそっちがスタンダードになっているだけなのかなと思ったりしているのですが、その書き方に慣れている人が多いならそっちの方が可読性は上がりそうですね
| if len(nums) <= 2: | ||
| return max(nums) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
問題の制約上は問題ないですが,numsが空だった場合どうしますか?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
強盗先の候補が0件という状態はおかしいので、ここではValueErrorを返します。
問題設定の状況によってはmax(nums, default=0)とでもしておけば良さそうです。
問題文:https://leetcode.com/problems/house-robber/description/