122. Best Time to Buy and Sell Stock 2#38
122. Best Time to Buy and Sell Stock 2#38dxxsxsxkx wants to merge 1 commit into121_best_time_to_buy_and_sell_stockfrom
Conversation
| } | ||
|
|
||
| int profit = 0; | ||
| for (int i = 1; i < prices.size(); i++) { |
There was a problem hiding this comment.
i++と書くより++iと書いたほうがいいみたいなことをどこかで見たことがある気がします。
あんまり詳しくないんですがi++よりも少しパフォーマンスが良いみたいです。
ただ今回の場合だとコンパイラがC++を機械語に変換するときに最適化されて両方変わらないコードが出来上がるかもしれません。
google c++ style guideには基本的に++iを使えみたいなことが書いてありました。
https://google.github.io/styleguide/cppguide.html#Preincrement_and_Predecrement
There was a problem hiding this comment.
| class Solution { | ||
| public: | ||
| int maxProfit(std::vector<int>& prices) { | ||
| if (prices.empty()) { |
There was a problem hiding this comment.
このif文はなくても動くのではないでしょうか?(試してないので間違ってたらすみません)
There was a problem hiding this comment.
あ、確かにそうですね。ありがとうございます。i の範囲と profit の初期化で対応できてました。
| public: | ||
| std::vector<std::vector<int>> memo; | ||
|
|
||
| int _helper(std::vector<int>& prices, int current_time, bool is_holding) { |
There was a problem hiding this comment.
「ヘルパー」という名前にしては複雑な処理をしているので、より具体的な名前にしたいです。
| return memo[current_time][is_holding]; | ||
| } | ||
|
|
||
| int result; |
| memo.assign(prices.size(), std::vector<int>(2, -1)); | ||
| return _helper(prices, 0, false); | ||
| } | ||
| public: |
| return _helper(prices, 0, false); | ||
| } | ||
| public: | ||
| std::vector<std::vector<int>> memo; |
There was a problem hiding this comment.
memoがどういう情報を持っているかコメントで補足するか、変数名を工夫すると良いと思いました。
bool型のis_holdingをsecond indexに入れているのに少し驚きましたが、一度理解できればわかりやすくて良い記法ですね。
|
|
||
| [参照](https://github.com/olsen-blue/Arai60/pull/38/changes#r1980557395):状態遷移を入れるとき、行列にするよりも配列を2つ持つ方が良いかも? | ||
|
|
||
| - あと自分の書き方だと `-1` がマジックナンバーになってる |
There was a problem hiding this comment.
メンバ変数としてstatic constexpr int UNCALCULATED = -1などとするのも可読性や保守性の観点からアリだと思います。今回は意味が自明なので-1でも伝わりました。
問題
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
次の問題
139. Word Break