


1. Buying a stock and then selling it is called one transaction.
2. You are not allowed to do multiple transactions at the same time. This means you have to sell the stock before buying it again.
Input: ‘n’ = 7, ‘prices’ = [3, 3, 5, 0, 3, 1, 4].
Output: 6
Explanation:
The maximum profit can be earned by:
Transaction 1: Buying the stock on day 4 (price 0) and then selling it on day 5 (price 3).
Transaction 2: Buying the stock on day 6 (price 1) and then selling it on day 6 (price 4).
Total profit earned will be (3 - 0) + ( 4 - 1) = 6.
The first line of each test case contains an integer 'n' denoting the number of days.
The second line of each test case contains 'n' space-separated integers, the array ‘prices’.
For each test case, return an integer denoting the maximum profit.
You do not need to print anything, it has already been taken care of. Just implement the given function.
This problem can be solved by solving its subproblems and then combining the solutions of the solved subproblems to solve the original problem. We will do this using recursion.
Basically, we have to buy the stock at the minimum possible price and sell at the maximum possible price, keeping in mind that we have to sell the stock before buying it again.
Below is the detailed algorithm:
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems multiple times. Thus, this problem exhibits overlapping subproblems. Thus, in this approach, we will eliminate the need for solving the same subproblems repeatedly.
The idea is to use memoization.
The detailed algorithm to fill the ‘maxProfit’ matrix is as follows:
We observe that the approach for the question goes in the following way:
First buy → First sell → Second buy → Second sell
Now, as, at the end we need maximum profit, let us think of it like this. Suppose you currently have Rs. 100 with you. You buy a stock of some amount, say ‘X’. The amount left with you is 100 - ‘X’. Now, if you sell the stock at an amount, say ‘ Y ‘, you are left with a total amount of 100 - ‘X’ + ‘Y’.
During the second transaction, you buy a stock of price ‘A’ and sell it at price ‘B’. The total amount becomes 100 - ‘X’ + ‘Y’ - ‘A’ + ‘B’. Now, all you need to do is maximize the money that you have.
Below is the detailed algorithm: