Close
Topic list
Best time to buy and sell stock II
MEDIUM
Dynamic Programming
Greedy
Arrays
Topics (Covered in this problem)
Problem solved
Skill meter
Dynamic Programming
-
-
Greedy
-
-
Arrays
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
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
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 II

Contributed by
Ratnesh
Medium
0/80
Share

## Problem Statement

#### Note: You can't sell a stock before you buy one.

##### Example:
``````Let's say, 'PRICES' = [7, 1, 5, 4, 3, 6]

Purchase stock on day two, where the price is one, and sell it on day three, where the price is five, profit = 5 - 1 = 4.
Purchase stock on day five, where the price is three, and sell it on day six, where the price is six, profit = 6 - 3 = 3.
Total Profit is 4+3 = 7. Hence we return 7.
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )
##### Sample Input 1 :
``````2
6
7 1 5 4 3 6
6
100 160 220 40 535 695
``````
##### Sample Output 1 :
``````7
775
``````
##### Explanation Of Sample Input 1 :
``````For test case 1:

'PRICES' = [7, 1, 5, 4, 3, 6]

Purchase stock on day two, where the price is one, and sell it on day three, where the price is five, profit = 5 - 1 = 4.
Purchase stock on day five, where the price is three, and sell it on day six, where the price is six, profit = 6 - 3 = 3.
Total Profit is 4+3 = 7. Hence we return 7.

For test case 2:

'PRICES' = [100, 160, 220, 40, 535, 695]

Purchase stock on day one, where the price is 100, and sell it on day three, where the price is 220, profit = 220 - 100 = 120.
Purchase stock on day four, where the price is 40, and sell it on day six, where the price is 695, profit = 695 - 40 = 655.

Total Profit is 120+655 = 775. Hence we return 775.
``````
##### Sample Input 2 :
``````2
5
5 4 3 2 1
1
13
``````
##### Sample Output 2 :
``````0
0
``````
Auto
Console