πDay 17. Stock Buy and Sell β Max 2 Transactions Allowed π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
In daily share trading, a trader buys shares and sells them on the same day. Given an array prices[] representing stock prices throughout the day, find the maximum profit a trader could have made with at most 2 transactions.
β Note: The second transaction can only start after the first one is complete (buy β sell β buy β sell).
π Example Walkthrough:
Example 1:
Input:
prices[] = [10, 22, 5, 75, 65, 80]Output:
87Explanation:
Buy at 10, sell at 22 β Profit = 12
Buy at 5, sell at 80 β Profit = 75
Total Profit = 12 + 75 = 87
Example 2:
Input:
Output:
Explanation:
Buy at 2, sell at 30 β Profit = 28
Buy at 8, sell at 80 β Profit = 72
Total Profit = 28 + 72 = 100
Constraints:
$1 \leq \text{prices.size()} \leq 10^5$
$1 \leq \text{prices[i]} \leq 10^5$
π― My Approach:
Optimized Greedy Approach
Use four variables:
b1(Best price to buy first stock)s1(Best profit after first sale)b2(Best price to buy second stock after first sale)s2(Best profit after second sale)
Iterate through prices and update these variables accordingly.
Return
s2(Maximum profit with at most two transactions).
Algorithm Steps:
Initialize
b1 = β,s1 = 0,b2 = β,s2 = 0.For each price
pin the array:Update
b1(Minimum price to buy first stock).Update
s1(Best profit after first sale).Update
b2(Best price to buy second stock).Update
s2(Best profit after second sale).
Return
s2.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), as we traverse the array once and perform a constant number of operations.
Expected Auxiliary Space Complexity: O(1), as we use only four variables.
π Solution Code
Code (C++)
β‘ Alternative Approaches
1οΈβ£ Dynamic Programming (O(N) Time, O(N) Space)
Algorithm Steps:
Define a
dp[i][j]table wheredp[i][j]represents the maximum profit achievable up to dayiwithjtransactions.Recurrence Relation: $[ dp[i][j] = \max(dp[i-1][j], \max_{k=0}^{i-1} (prices[i] - prices[k] + dp[k][j-1])) ]$
Use a space-optimized 1D DP array to reduce
O(NΒ²)complexity toO(N).
β
Time Complexity: O(N)
β
Space Complexity: O(N)
2οΈβ£ Greedy + Prefix/Suffix Array (O(N) Time, O(N) Space)
Algorithm Steps:
Use prefix max profit (
left[i]) to track max profit from 0 to i.Use suffix max profit (
right[i]) to track max profit from i to N-1.Merge results to get the maximum of
left[i] + right[i+1].
β
Time Complexity: O(N)
β
Space Complexity: O(N)
3οΈβ£ Recursive + Memoization (O(N) Time, O(NΓ2) Space)
Algorithm Steps:
Use a recursive function
maxProfit(index, transactions, holding)that computes:If you are holding a stock, you can sell or keep it.
If you don't have a stock, you can buy or skip.
Memoization (
dp[i][j][h]):i: Day index.j: Transactions used (max 2).h: Holding status (0or1).
β
Time Complexity: O(N)
β
Space Complexity: O(NΓ2)
Comparison of Approaches
Approach
β±οΈ Time Complexity
ποΈ Space Complexity
β Pros
β οΈ Cons
Greedy (Optimized)
π’ O(N)
π’ O(1)
Best for large inputs
Hard to intuitively understand
DP (2D Table)
π’ O(N)
π΄ O(N)
Easy to implement, intuitive
Higher space usage
Prefix-Suffix Arrays
π’ O(N)
π‘ O(N)
Easier to understand
Extra space usage
Recursive + Memoization
π’ O(N)
π΄ O(NΓ2)
Intuitive recursion approach
High memory usage
β Best Choice?
If you want best efficiency: Use Greedy (Optimized) approach.
If you prefer DP-style tabulation: Use 2D DP Approach.
If you like prefix-suffix tricks: Use Prefix-Suffix Arrays.
If you like recursion: Use Recursive + Memoization.
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated