Open
Conversation
naoto-iwase
reviewed
Dec 1, 2025
|
|
||
| for price in &prices[1..] { | ||
| min_price = min_price.min(*price); | ||
| max_price = max_price.max(*price - min_price); |
Comment on lines
+38
to
+41
| let mut min_price = match prices.len() { | ||
| 0 => return 0, | ||
| _ => prices[0], | ||
| }; |
There was a problem hiding this comment.
ここですが、pricesが空かどうかのチェックと、空の場合のearly return、空でない場合のmin_priceの初期化と、複数の関心が1つのmatchに押し込められていて読みにくさを感じました。
一つは、シンプルに下記のようにする方法が最も読みやすいと感じます。
if prices.is_empty() {
return 0;
}
let mut min_price = prices[0];もしくは、matchの書き方をリスペクトして、以下はどうでしょうか。
impl Solution {
pub fn max_profit(prices: Vec<i32>) -> i32 {
let (first, remainings) = match prices.split_first() {
Some(x) => x,
None => return 0,
};
let mut min_price = *first;
let mut max_profit = 0;
for &price in remainings {
min_price = min_price.min(price);
max_profit = max_profit.max(price - min_price);
}
max_profit
}
}少なくともmin_priceの初期化という関心は分離することができていると思います。
There was a problem hiding this comment.
2つ目について、下の方が自然ですかね。
let Some((first, remainings)) = prices.split_first() else {
return 0;
};
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題: 121. Best Time to Buy and Sell Stock
次に解く問題: 122. Best Time to Buy and Sell Stock II
ファイルの構成:
./src/bin/<各ステップ>.rs