Skip to content

53. Maximum Subarray#25

Merged
huyfififi merged 8 commits intomainfrom
leetcode-53-maximum-subarray
Jul 2, 2025
Merged

53. Maximum Subarray#25
huyfififi merged 8 commits intomainfrom
leetcode-53-maximum-subarray

Conversation

@huyfififi
Copy link
Copy Markdown
Owner

@huyfififi huyfififi self-assigned this Jun 30, 2025
@huyfififi huyfififi marked this pull request as ready for review June 30, 2025 07:25

## 他の解法

Follow upでdivide and conquerが仄めかされていたので、どうにか問題を分割できないか考えていたのだが、思いつかなかった。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

役に立つかはわかりませんが、以下自分の理解です。

与えられた配列を中央で分けて、左の部分配列と右の部分配列でそれぞれ最大の和を再帰的に探していきます。が、中央を跨ぐ部分配列も最大の和が作れる候補になり得るので、

  • 分割
    • 配列を中央で分ける
  • 統治
    1. 左半分の最大和を再帰的に求める
    2. 右半分の最大和を再帰的に求める
    3. 中央を跨ぐ最大和を求める(配列の左端と右端を広げる方向に動かし、和が最大になる部分を見つける)
  • 結合
    • i.~iii.で最も大きいものを最大和とする

のような関数を用意して実装する必要があります。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

丁寧にありがとうございます!まだ中央を跨ぐ最大和の扱いがしっくり頭に収まらないのですが、もう少し考えてみます...

def maxSubArray(self, nums: list[int]) -> int:
cumulative_sum = 0
min_cumulative_sum_so_far = 0
max_subarray_sum = -float("inf")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

max_subarray_sum は int なので、float("inf") ではなく sys.maxsize を選ぶ考え方もあるようです。

An integer giving the maximum value a variable of type Py_ssize_t can take
https://docs.python.org/3/library/sys.html#sys.maxsize

Copy link
Copy Markdown
Owner Author

@huyfififi huyfififi Jun 30, 2025

Choose a reason for hiding this comment

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

コメントありがとうございます!私は、sys.maxsizeはプラットフォーム依存・Pythonのintには上限がなくsys.maxsizeを超えうる、といった問題がある一方、PythonではDuck-Typingが推奨されているような気がするので、floatintのミスマッチは大きな問題ではないと考えています。また、sys.maxsizelistなどの最大データ長を表し、それをとりうる最大の値として用いるのは、少しミスリーディングかな?とも思っています。が、実際他の方々がどう思うかはわかりません...

for num in nums:
max_ending_subarray_sum = max(max_ending_subarray_sum + num, num)
max_subarray_sum = max(max_subarray_sum, max_ending_subarray_sum)
return max_subarray_sum
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

読みやすかったです。特に問題ないと思います。

@huyfififi huyfififi merged commit a5229ca into main Jul 2, 2025
@huyfififi huyfififi deleted the leetcode-53-maximum-subarray branch July 2, 2025 19:20
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.

2 participants