Skip to content

add: Best Time to Buy and Sell Stock#22

Open
rossy0213 wants to merge 1 commit intomainfrom
arai60-38
Open

add: Best Time to Buy and Sell Stock#22
rossy0213 wants to merge 1 commit intomainfrom
arai60-38

Conversation

@rossy0213
Copy link
Copy Markdown
Owner

@rossy0213 rossy0213 commented May 25, 2024

// Time spend: 04:32
func maxProfit(prices []int) int {
buy := -prices[0];
sell := buy + 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.

この部分、何か考えて初期化していますか。

// Space complexity: 1
// Time spend: 04:32
func maxProfit(prices []int) int {
buy := -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.

これ、負の値を入れたのが、min を定義するのが億劫という理由だけのように見えていますが、なにか理由ございますでしょうか。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

購入価格を負の数で表すのはなるほどとなりました!
個人的には正の数で表して、利益は引き算で計算するやり方が直感的でした。

// Space complexity: 1
// Time spend: 04:32
func maxProfit(prices []int) int {
buy := -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.

購入価格を負の数で表すのはなるほどとなりました!
個人的には正の数で表して、利益は引き算で計算するやり方が直感的でした。

return sell
}

func max(a, b int) int {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Go全然知らないのですが現在は組み込み関数のmaxがあるようです?
https://future-architect.github.io/articles/20230815a/

Comment on lines +8 to +9
buy = max(buy, -p)
sell = max(sell, buy + p)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

buy, sellがそれぞれ最小購入価格、最大売却価格の意味を持つことを変数名で表すとわかりやすいかと思いました。
minBuyingPrice, maxSellingPrice

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.

3 participants