Skip to content

Conversation

@TORUS0818
Copy link
Owner

max_money_skipped_i = nums[0]
max_money_robbed_i = nums[1]
for i in range(2, len(nums)):
max_money_skipped_i, max_money_robbed_i = (
Copy link

Choose a reason for hiding this comment

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

変数のアンパックを使っていて変数名が長いとごてごてしますね。
max_money_*_i が一つの式に5回出てくるのは迷彩のようです。

現場では多くの場合、def の後に docstring を書くし、関数名ももう少ししっかりしているので、もう少し文脈があるはずです。また、変数名にコメントをつけるのも一つでしょう。
https://peps.python.org/pep-0257/#what-is-a-docstring


# numsのi番目を盗んだかどうかで場合わけ
# i = 1で初期化しておく
max_money_skipped_i = nums[0]

Choose a reason for hiding this comment

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

_iの部分がちょっと気になりました、なんかループの中でi番目のi-1番目として使われるのでややこしいなと感じました。まあこの部分がなくても良いのかなとも思います。

max_money_skipped_i = nums[0]
max_money_robbed_i = nums[1]
for i in range(2, len(nums)):
max_money_skipped_i, max_money_robbed_i = (

Choose a reason for hiding this comment

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

本当はこっちの方が読みやすいと思うのですが、仕方がないですね。

max_money_skipped_i = max(max_money_skipped_i, max_money_robbed_i)
max_money_robbed_i = max_money_skipped_i + nums[i]

Choose a reason for hiding this comment

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

いっそのこと別途変数を用意してしまうとか?少しやりすぎですかね?

class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums) <= 2:
            return max(nums)

        max_money_skipped_last = nums[0]
        max_money_robbed_last = nums[1]
        for i in range(2, len(nums)):
            max_money_skipped = max(max_money_skipped_last, max_money_robbed_last)
            max_money_robbed = max_money_skipped_last + nums[i]
            max_money_skipped_last = max_money_skipped
            max_money_robbed_last = max_money_robbed

        return max(max_money_skipped_last, max_money_robbed_last)

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
いえ、こちらの方が実態とあっていて良いですね。

# numsのi番目を盗んだかどうかで場合わけ
# i = 1で初期化しておく
max_money_skipped_i = nums[0]
max_money_robbed_i = nums[1]
Copy link

Choose a reason for hiding this comment

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

個人的にはskippedを0、robbedをnum[0]にした方が好みです。(初期化の意図もわかりやすいので)
その場合、early returnする必要もなくなりますね

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
なるほど、気がつきませんでした。

2つ前の値を使うからi=2スタートだと決め打ちしていたんだと思います。
最初の家で盗んだかどうかを考えれば自然に思いつきますね。

@TORUS0818 TORUS0818 mentioned this pull request Dec 6, 2024
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