Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Best Time to Buy and Sell Stock III
HARD
52 upvotes
Arrays
Dynamic Programming
Greedy
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Dynamic Programming
-
-
Greedy
-
-
Arrays
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Best Time to Buy and Sell Stock III

Contributed by
Himanshu Tanwar
Hard
yellow-spark
0/120
Share
52 upvotes

Problem Statement

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. 
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
1
7
3 3 5 0 3 1 4
Sample output 1:
6
Explanation of Sample output 1:
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. 
Sample Input2:
1 
5
5 4 3 2 1
Sample Output2:
0
Explanation of Sample output 2
It's better to not do any transaction as the prices of the stock are decreasing. 
Reset Code
Full screen
Auto
copy-code
Console