Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Best time to buy and sell stock II
MEDIUM
Dynamic Programming
Greedy
Arrays
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 II

Contributed by
Ratnesh
Medium
yellow-spark
0/80
Share
0 upvotes

Problem Statement

You are given an array of integers, 'PRICES' of size 'N', where 'PRICES[i]' is the price of a given stock on 'i'th day.

On each day, you may decide to buy and sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it and then immediately sell it on the same day.

Return the maximum profit you can achieve.

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
Reset Code
Full screen
Auto
copy-code
Console