Buy and Sell Stock
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
CodingNinjas
author
3y
Recursion
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
CodingNinjas
author
3y
Memoization
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
CodingNinjas
author
3y
Dynamic Programming
- 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
CodingNinjas
author
3y
Optimized Dynamic Programming
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
Add answer anonymously...
Top Josh Technology Group Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
>
Josh Technology Group Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app