You are Harshad Mehta’s friend. He told you the price of a particular stock for the next ‘N’ days. You can either buy or sell a stock. Also, you can only complete at most 2-transactions. Find the maximum profit that you can earn from these transactions. You can take help from Mr. Mehta as well.
Note
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 Format:
The first line contains a single integer 'T' representing the number of test cases.
Then 'T' test cases follow:
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, where the 'i-th' element is the price of the particular stock on the 'i-th' day.
Output Format :
For each test case, the first and only line of output contains an integer denoting the maximum profit.
The output of every test case is printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 5 * 10^4
0 <= price <= 10^3
Where ‘price’ is the price of the stock on each day.
Time Limit: 1 sec
A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.
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 h...read more
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 m...read more
- The idea is to create a 2-D array ‘MAXPROFIT’ of size size (3) * (N).
- Initially, all the elements of the ‘MAXPROFIT’ matrix will be 0.
- Now, the value ‘MAXPROFIT[i][j]’ denotes the max...read more
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...read more
Top Mobikwik Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month