Skip to content

53. Maximum Subarray#32

Open
dxxsxsxkx wants to merge 1 commit into300_longest_increasing_subsequencefrom
53_maximum_subarray
Open

53. Maximum Subarray#32
dxxsxsxkx wants to merge 1 commit into300_longest_increasing_subsequencefrom
53_maximum_subarray

Conversation

@dxxsxsxkx
Copy link
Owner

min_cumsum = std::min(min_cumsum, cumsum);
}

return max_sum;
Copy link

Choose a reason for hiding this comment

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

いいと思います。個人的にはmax_sumはresultとかmax_cumsum_diffとかにするかもしれません。

@@ -0,0 +1,16 @@
#include <limits>

Choose a reason for hiding this comment

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

Suggested change
#include <limits>
#include <algorithm>

std::max<algorithm>にあるものと思います。
(手元の環境ではこのままでもコンパイルが通りました。詳しくは調べられていないのですが、環境によってはstd::vectorをincludeすると内部でstd::algorithmも入ってくるみたいです。)

int maxSubArray(std::vector<int>& nums) {
int cumsum = 0;
int min_cumsum = 0;
int max_sum = nums[0];

Choose a reason for hiding this comment

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

potrueさんと同じ指摘になってしまいますが、min_cumsumは"累積"和であることが説明されているのに対して、max_sumはなんの和なのかパッと見わかりづらいなと思いました。max_subarray_sumなどとするとさらに安全かと思います。

愚直に二重ループでやろうと試みた。$i$ について、$0 < j < i$ となる要素を `nums[i]` に順番に足していって、都度都度評価する。うまくいかず。

- ChatGPTに聞いてみて、メモの0が原因だとわかる。部分配列の和は負になりうるので、初期値を変える必要がある。外側のループの中で `nums[i]` で初期化したらこの部分はうまくいった。
- で、TLEになった。 `nums.length <= 10^5` で$O^2$ なのでやむない。見積もりをできる様にならなければ...
Copy link

Choose a reason for hiding this comment

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

O(n2) と書くのが一般的だと思います。

また、時間計算量の見積もりができるようになったら、処理時間の見積もりもできるようになるとよいと思います。処理時間の見積もりについては、以下のコメントをご参照ください。
Yuto729/LeetCode_arai60#16 (comment)

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。今後やってみます。

class Solution {
public:
int maxSubArray(std::vector<int>& nums) {
int cumsum = 0;
Copy link

Choose a reason for hiding this comment

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

cumsum という単語は numpy 等ではしばしば見かけると思うのですが、変数名として一般的というほどではないように思います。また、単語から文字を削って変数名とした場合、読み手に取って認知負荷が上がる場合があります。これについては以下のコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

public:
int maxSubArray(std::vector<int>& nums) {
int current = nums[0];
int best = nums[0];
Copy link

Choose a reason for hiding this comment

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

他の書き方として、nums.front() もありますね。

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