Skip to content

Create 122. Best Time to Buy and Sell Stock II.md#38

Open
tokuhirat wants to merge 1 commit intomainfrom
122.-Best-Time-to-Buy-and-Sell-Stock-II
Open

Create 122. Best Time to Buy and Sell Stock II.md#38
tokuhirat wants to merge 1 commit intomainfrom
122.-Best-Time-to-Buy-and-Sell-Stock-II

Conversation

@tokuhirat
Copy link
Owner

This Problem
122. Best Time to Buy and Sell Stock II
Next Ploblem
139. Word Break
言語: Python

for i in range(len(prices) - 1):
if prices[i] < prices[i + 1]:
max_profit += prices[i + 1] - prices[i]
return max_profit

Choose a reason for hiding this comment

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

特に問題ないと思います。
個人的には i を day に変えると、より直感的になるかと思っています。

Copy link
Owner Author

Choose a reason for hiding this comment

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

day は自分の選択肢にはなかったので今後は選択肢に入れるようにします。ありがとうございます。

max_profit = 0
index = 0
while index < len(prices):
valley_index = find_next_lowest(index)

Choose a reason for hiding this comment

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

peakの対義語として、bottomでも良いかもしれません。
また、関数名で使われているので、そのままlowest, highestでも良いかと思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。確かに関数名と合わせた方がわかりやすいですね。

### プルリクやドキュメントを参照
- https://github.com/hayashi-ay/leetcode/pull/56/files
- https://github.com/olsen-blue/Arai60/pull/38/files
- 株を持っている/いない場合の保有現金最大値を管理する方法

Choose a reason for hiding this comment

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

DPでも(個人的に少し直感的ではないですが)解けるので、解いてみても良いかと思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

DP で書いてみました。私もあまり直観的ではないなと感じています。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        cash_with_stock = -prices[0]
        cash_without_stock = 0
        for i in range(1, len(prices)):
            prev_cash_with_stock = cash_with_stock
            cash_with_stock = max(cash_with_stock, cash_without_stock - prices[i])
            cash_without_stock = max(cash_without_stock, prev_cash_with_stock + prices[i])
        return cash_without_stock

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