-
-
Notifications
You must be signed in to change notification settings - Fork 101
188. Best Time to Buy and Sell Stock IV.cpp #268
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
base: main
Are you sure you want to change the base?
Conversation
Reviewer's GuideThis PR adds a new C++ solution for LeetCode 188 using a 3D memoized recursion that tracks the current day, buy/sell state, and remaining transactions to compute maximum profit. Class diagram for the new Solution class (Best Time to Buy and Sell Stock IV)classDiagram
class Solution {
+vector<vector<vector<int>>> dp
+int profit(vector<int>& prices, int i, int isBuy, int k)
+int maxProfit(int k, vector<int>& prices)
}
Solution : profit(prices, i, isBuy, k) uses dp
Solution : maxProfit(k, prices) uses profit(prices, i, isBuy, k)
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
|
@SjxSubham Please 🙏 check this PR also. |
|
@SjxSubham, please merge this PR. |
|
@kaif969 U r only allowed to contribute upto two solutions only... |
PR Title Format: 188. Best Time to Buy and Sell Stock IV.cpp
Intuition
We want to maximize profit by making at most
kstock transactions. Each day, we can choose to buy, sell, or skip. Using recursion with memoization (3D DP), we track the day, buy/sell state, and remaining transactions.Approach
Use a recursive function profit(prices, i, isBuy, k):
Base case: if we reach the end of prices or no transactions left, return 0.
If isBuy == 1: choose to buy today or skip.
If isBuy == 0: choose to sell today or skip.
Store results in a 3D DP array dp[i][isBuy][k] to avoid recomputation.
Finally, call profit(prices, 0, 1, k) starting from day 0 with buy allowed.
Code Solution (C++)
Related Issues
#261
By submitting this PR, I confirm that:
Summary by Sourcery
Summary by Sourcery
New Features: