-
Notifications
You must be signed in to change notification settings - Fork 0
Solved Arai60/53. Maximum Subarray #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
|
||
| ## Step 3. Final Solution | ||
|
|
||
| - max()を使わずにif文を使う方が関数呼び出しがない分速そう |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
どのくらい早くなるか気になりました。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
読みやすかったです。prefix_sum に関する処理をまとめてループ冒頭に書くのもありかなと思いました。
問題文:https://leetcode.com/problems/maximum-subarray/description/