Skip to content

Conversation

@Satorien
Copy link
Owner

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])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

max() に渡す前にスライスを使い、部分 list のコピーを作っている点が、処理が定数倍重くなりそうだなと感じました。ただ、 Python のようにもともと重い言語で定数倍の速度差を気にするのも微妙だと思いました。

Copy link
Owner Author

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]]
Copy link

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]))

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] を定義していることがわかりやすいかなと感じます。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

確かに先に作ってしまう方がよく見る気がしますね。C言語とかでリスト長を指定する流れからそっちがスタンダードになっているだけなのかなと思ったりしているのですが、その書き方に慣れている人が多いならそっちの方が可読性は上がりそうですね

Comment on lines +12 to +13
if len(nums) <= 2:
return max(nums)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

問題の制約上は問題ないですが,numsが空だった場合どうしますか?

Copy link
Owner Author

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)とでもしておけば良さそうです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants