Skip to content

maximum-subarray#25

Open
n6o wants to merge 1 commit intomainfrom
maximum-subarray
Open

maximum-subarray#25
n6o wants to merge 1 commit intomainfrom
maximum-subarray

Conversation

@n6o
Copy link
Owner

@n6o n6o commented Mar 11, 2026

if not nums:
return 0

n = len(nums)
Copy link

Choose a reason for hiding this comment

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

好みかと思いますが、len(nums)のままの方が好みです。nは変数の中身の情報を与えておらず、コードが長くなった時や複数の配列あるいは複数の次元を持った時などにm,n,k,lと変数が増えると逐一定義を確認することになった経験があるからです。

sums_table[i][i] = nums[i]
max_sum = max(max_sum, sums_table[i][i])

for j in range(1, i):
Copy link

Choose a reason for hiding this comment

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

こちらの説明ではsums_table[i][j]は「nums[i]からnums[j]までの和」というふうに捉えていると思うので、コードのこの箇所は

for j in range(i + 1, n)

ではないでしょうか?

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
ご指摘のとおり、 range(i+1, n) が正しいです。

max_sum = max(max_sum, sums[i])

for j in range(i):
sums[j] = sums[j] + nums[i]
Copy link

Choose a reason for hiding this comment

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

sums[j] += nums[i]で良いと思います。

return 0

max_sum = nums[0]
running_sum = nums[0]
Copy link

Choose a reason for hiding this comment

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

ここの変数名は自分もドンピシャなものが考えついておらず恐縮ですが、この変数名だと中身を特定できる程度の説明力がないため、中身をコードから推測する必要がありました。つまり「連続する和」という変数名から「(forで取り出した)numが最後に来る連続した部分列の和」というロジックを推測するのは難しいということです。max_sumについても、一瞬「running_sumもmaxをとっているし、sumではあるよな?max_sumはなんだろう?」と考えました。

running_sumもmax_sumも「最大値を取り続ける」値なので、「何の」最大をとっているのかを明示すると良いと思いました。たとえばmax_running_sum_with_nummax_subarray_sumなど。

あるいは単純に一言変数を説明するコメントを書いてもこの問題は解決されるでしょう。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
読み手を想像すると、 max_subarray_sum などもう少し説明的な変数名になるよう工夫すべきでした。

Comment on lines +162 to +165
max_sum = nums[0]
running_sum = nums[0]
for i in range(1, len(nums)):
running_sum = max(nums[i], running_sum + nums[i])
Copy link

Choose a reason for hiding this comment

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

nums[0] を特別扱いしない書き方も検討できると良いと思いました。私はこちらの方が好みです。

Suggested change
max_sum = nums[0]
running_sum = nums[0]
for i in range(1, len(nums)):
running_sum = max(nums[i], running_sum + nums[i])
max_sum = -float('inf')
running_sum = 0
for num in nums:
running_sum = max(num, running_sum + num)

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.

3 participants