Skip to content

121.best time to buy and sell stock#37

Open
t9a-dev wants to merge 2 commits intomainfrom
121.Best-Time-to-Buy-and-Sell-Stock
Open

121.best time to buy and sell stock#37
t9a-dev wants to merge 2 commits intomainfrom
121.Best-Time-to-Buy-and-Sell-Stock

Conversation

@t9a-dev
Copy link
Copy Markdown
Owner

@t9a-dev t9a-dev commented Dec 1, 2025

問題: 121. Best Time to Buy and Sell Stock
次に解く問題: 122. Best Time to Buy and Sell Stock II
ファイルの構成: ./src/bin/<各ステップ>.rs

Comment thread src/bin/step2.rs

for price in &prices[1..] {
min_price = min_price.min(*price);
max_price = max_price.max(*price - min_price);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

max_profitの方が適切だと思います。

Comment thread src/bin/step2.rs
Comment on lines +38 to +41
let mut min_price = match prices.len() {
0 => return 0,
_ => prices[0],
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここですが、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の初期化という関心は分離することができていると思います。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2つ目について、下の方が自然ですかね。

    let Some((first, remainings)) = prices.split_first() else {
        return 0;
    };

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.

2 participants