Skip to content

Conversation

nanae772
Copy link
Owner

@nanae772 nanae772 commented Oct 7, 2025

問題リンク

53. Maximum Subarray

問題文の概要

Given an integer array nums, find the with the largest sum, and return its sum.

次に解く予定の問題

Unique Paths

- 最終的な答えはmax(dp)

と考えられて、よく見るとdp[i]を計算するときにdp[i-1]しか使ってないので適当な変数にすると
Kadane's algorithmになる。
Copy link

Choose a reason for hiding this comment

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

そうですね。
prefix_sum - min_prefix_sum を整理してもこれになります。

Copy link

@huyfififi huyfififi left a comment

Choose a reason for hiding this comment

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

良いと思います 👍 読んでいて特に引っかかりは覚えませんでした!

@@ -0,0 +1,11 @@
class Solution:
def maxSubArray(self, nums: list[int]) -> int:
if not nums:

Choose a reason for hiding this comment

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

空の入力に対して0を返されていますが、後ろのロジックでは空の入力 -> 0 を最大値として許容しておらず、少しだけ統一感がないような気がしました。
maxSubArray([]) = 0とされていますが、後ろのロジックで[-2, -3]を考えるとき[] -> 0 を最大値として扱わず、[-2] -> -2 が答えになるので、場所によって空の(部分)列?に対する扱いが変わっているように思います。
なので、例外を出す方が無難かな、と思いますが、そこまで自信はありません。

Copy link
Owner Author

Choose a reason for hiding this comment

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

確かに空配列の入力に対してどうするかはもう少しちゃんと考えるべきでした。

今回の要件としてsubarrayはnon-emptyであると問題で要請されているので、空配列はsubarrayを持たないため計算できないものとして例外を投げるのがよかったかなと自分でも思います。
あるいは例外を起こして処理を止めたくない場合は「計算できなかった」ということを示すNoneやfloat('nan')を返す、などでもよいかもしれないと思いました。

コメントいただきありがとうございます。

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