-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Updated pattern for best-time-to-buy-and-sell-stock #129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Despite the stated in related topics - by fact, this task is not about dynamic programming. Also, there are lot of comments about this in the Solution tab.
Thanks for this @cub-uanic! I'm looking over the Solution tab and seeing DP approaches, or a "state machine" approach. Are you able to link/provide a deeper explanation?
Hey @cub-uanic - looping back here to see if you have time to answer my initial question!
Best time to buy and sell can be answered as a dp problem, and that too in both forward and backward iterations.
def maxProfit(prices: List[int]) -> int: dp = [0] * len(prices) dp[-1] = prices[-1] res = 0; for i in reversed(range(len(prices) - 1)): dp[i] = prices[i] if prices[i] > dp[i + 1] else dp[i + 1] res = max(res, dp[i] - prices[i]); return res
def maxProfit(prices: List[int]) -> int: dp = [0] * len(prices) dp[0] = prices[0] res = 0 for i in range(1, len(prices)): dp[i] = prices[i] if dp[i - 1] > prices[i] else dp[i - 1] res = max(res, prices[i] - dp[i]) return res
Basically we are storing best on the right of current, and checking with current if difference yields best profit, or we could check cheapest to the left and compare with current and check profit and store max.
Since we only need one value, you can always optimize it to O(1) space, and at that point it starts to look a lot like greedy, rather than dp, I personally classify such things as optimized 1d dp as it is derivative of it, but one could view them as greedy if they wish to.
It sort of falls in the grey area of is it dp, it is greedy, similar to kadane's.
Closing as no follow-up from @cub-uanic - feel free to provide more context/links and I'll be happy to reconsider! Ty!
Reopening to merge after a great explanation by another contributor here: #152 (comment)!
Actually on a second pass, we want to update here instead:
leetcode-patterns/src/data/index.js
Line 436 in 606ff62
I'll close this & reopen a new patch to do so.
Despite the stated in related topics - by fact, this task is not about dynamic programming.
Also, there are lot of comments about this in the Solution tab.