Skip to content

Conversation

Satorien
Copy link
Owner

@Satorien Satorien commented Jun 18, 2025

@Satorien Satorien changed the title Solved 53. Maximum Subarray.md Solved Arai60/53. Maximum Subarray Jun 18, 2025

## Step 3. Final Solution

- max()を使わずにif文を使う方が関数呼び出しがない分速そう
Copy link

Choose a reason for hiding this comment

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

どのくらい早くなるか気になりました。

Copy link

Choose a reason for hiding this comment

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

確かに気になったので以下の方法で調べたところ、2倍以上違うようでした

>>> def func_without():
...     max_num = 0
...     start = time.perf_counter()
...     for i in range(100000000):
...             if i > max_num:
...                     max_num = i
...     return time.perf_counter() - start
...
>>> print(func_without())
2.5938715199999933
>>> def func_with():
...     max_num = 0
...     start = time.perf_counter()
...     for i in range(100000000):
...             max_num = max(max_num, i)
...     return time.perf_counter() - start
...
>>> print(func_with())
6.753082412000367

Copy link

Choose a reason for hiding this comment

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

重要なのは比ではなくて時間です。

一回あたり、上(条件分岐 + 代入)が 26 ns、下(max + 代入)が 68 ns ですね。
概ね、Python の関数呼び出しは数十 ns くらいと思いますので妥当な結果でしょう。

こういう風に、秒で評価しましょう。

prefix_sum += num
if max_sum < prefix_sum:
max_sum = prefix_sum
if prefix_sum < 0:

Choose a reason for hiding this comment

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

読みやすかったです。prefix_sum に関する処理をまとめてループ冒頭に書くのもありかなと思いました。

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