Buy and Sell Stock - III Problem Statement

Given an array prices where the ith element represents the price of a stock on the ith day, your task is to determine the maximum profit that can be achieved at the end of the ith day. You are allowed to complete at most two transactions.

Remember, you can only engage in one transaction at a time, meaning you must sell the stock before buying again. Also, it is not necessary to execute exactly two transactions.

Input:

The first line of input contains an integer 'T' indicating the number of test cases.

The first line of each test case contains a single integer 'N', the length of the array prices.

The second line of each test case consists of 'N' space-separated integers, each representing an element of the array prices.

Output:

For each test case, output the maximum profit that can be achieved by selling the stocks.

Example:

Given the input:

1
6
3 3 5 0 0 3 1 4

The expected output is:

6

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 10^4
  • 0 <= prices[i] <= 10^9
Note
You do not need to print anything; it has already been taken care of.
AnswerBot
4mo

Determine the maximum profit that can be achieved by selling stocks with at most two transactions.

  • Iterate through the array and calculate the maximum profit that can be achieved by selling at each day...read more

Anonymous
3y

very good question

thanks

Help your peers!
Select
Add answer anonymously...
Cognizant Big Data Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits