New update is available. Click here to update.
Close
Topic list
Best Time to Buy and Sell Stock
MEDIUM
20 mins
Arrays
Topics (Covered in this problem)
Problem solved
Skill meter
Arrays
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
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

Contributed by
Arindam Majumder
Medium
0/80
Avg time to solve 20 mins
Success Rate 80 %
Share

## Problem Statement

#### Note:

``````You can’t sell without buying first.
``````
##### For Example:
``````For the given array [ 2, 100, 150, 120],
The maximum profit can be achieved by buying the stock at minute 0 when its price is Rs. 2 and selling it at minute 2 when its price is Rs. 150.
So, the output will be 148.
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )
##### Sample Input 1:
``````2
4
1 2 3 4
4
2 2 2 2
``````
##### Sample Output 1:
``````3
0
``````
##### Explanation For Sample Output 1:
``````For the first test case, it’s optimal to buy the stock at minute 0 and sell it at minute 3 to get a maximum profit of 3.

For the second test case, the maximum profit will be 0 for all possible ways of buying and selling stock.
``````
##### Sample Input 2:
``````2
6
17 20 11 9 12 6
4
98 101 66 72
``````
##### Sample Output 2:
``````3
6
``````
Auto
Console