Skip to content

Conversation

@Ryotaro25
Copy link
Owner

問題へのリンク
https://leetcode.com/problems/maximum-product-subarray/description/

問題文(プレミアムの場合)

備考

次に解く問題の予告
15. 3Sum

フォルダ構成
LeetCodeの問題ごとにフォルダを作成します。
フォルダ内は、step1.cpp、step2.cpp、step2_2.cpp、step3.cppとmemo.mdとなります。

memo.md内に各ステップで感じたことを追記します。


## 他の解法
負の数が偶数個あると最大になりうる特性を活かして途中でswapすることで
自分のstep1で行った3パターンから2パターンへ比較回数を減らすことができる(step2_2で実装)
Copy link

Choose a reason for hiding this comment

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

step 2 が私は愚直で気に入りました。このあたりで解いている人たちがいます。
https://discord.com/channels/1084280443945353267/1196498607977799853/1358736384604766238

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。
小田さんの解法はstep2_2に近いので理解できました。
野田さんの解法は他のコメント、解説を読んでギリギリ理解できたような感覚です。きちんと言語化できないですが負の数が奇数になる場合を両サイドから見ていくことで避けていると理解しました。

int max_product_so_far = nums[0];
int min_product_so_far = nums[0];
for (int i = 1; i < nums.size(); i++) {
int temp_max_so_far = max(nums[i], max(max_product_so_far * nums[i], min_product_so_far * nums[i]));
Copy link

Choose a reason for hiding this comment

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

Python のようにしたければ

tie(a, b) = make_pair(b, a);

というのが一応ありますが、素直に両方の変数を new_max, new_min とでも一度置いてから更新のほうが読みやすいでしょう。


return max_product;
}
}; No newline at end of file

Choose a reason for hiding this comment

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

スクリーンショット 2025-07-30 5 18 35 discord内で見つけた他の方のコメントです。 https://discord.com/channels/1084280443945353267/1196498607977799853/1240265127207632896

参考記事:https://qiita.com/raiga0310/items/8a0df87ecb3e0b0c676a

Copy link
Owner Author

Choose a reason for hiding this comment

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

@Apo-Matchbox
確認有り難とうございます。漏れておりました。。。

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.

4 participants