
Best Time to Buy and Sell Stock II (medium)
Problem Statement
You are given a prices array containing the integers, where price[i] refers to the stock price on i<sup>th</sup> day.
You are allowed to do as many transactions as you like (buy one and sell one stock multiple times). You cannot engage in multiple transactions simultaneously (you must sell the stock before you buy again). However, you can buy again on the same day after selling.
Find the maximum profit you can achieve from these transactions.
Examples
-
Example 1:
- Input:
[4, 9, 2, 3, 6, 8] - Expected Output:
11 - Justification: Buy on day 1 (price = 4) and sell on day 2 (price = 9), profit = 9-4 = 5. Then buy on day 3 (price = 2) and sell on day 6 (price = 8), profit = 8-2 = 6. Total profit is 5 + 6 = 11.
- Input:
-
Example 2:
- Input:
[5, 3, 6, 2, 5, 4] - Expected Output:
6 - Justification: Buy on day 2 (price = 3) and sell on day 3 (price = 6), profit = 6-3 = 3. Then buy on day 4 (price = 2) and sell on day 5 (price = 5), profit = 5-2 = 3. Total profit is 3 + 3 = 6.
- Input:
-
Example 3:
- Input:
[10, 8, 6, 5, 4, 2] - Expected Output:
0 - Justification: Prices are decreasing each day, so there's no opportunity to make a profit. It is best not to make any transactions.
- Input:
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory