23. Buy and Sell a Share at most twice
The problem can be found at the following link: Question Link
My Approach
To solve this problem, I utilize a dynamic programming approach to track the maximum profit achievable by making transactions at each day. Specifically:
I iterate through the prices array once to compute the maximum profit that can be obtained by making one transaction up to that day and store it in the 'left' array.
Then, I iterate through the prices array in reverse to compute the maximum profit that can be obtained by making two transactions. During this iteration, I combine the profit obtained from the first transaction (stored in 'left' array) with the profit obtained by selling on the current day.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity of this approach is
O(n)
, where n is the number of elements in theprice
vector.Auxiliary Space Complexity: The auxiliary space complexity is
O(n)
, where n is the number of elements in the 'price' vector.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated