Back to ArraysBest Time to Buy and Sell Stock II
Medium

Best Time to Buy and Sell Stock II

MediumRecommendedGreedy Array Patterns

Given an array of daily stock prices, find the maximum profit achievable by completing as many non-overlapping buy-sell transactions as you like.

Examples

Example 1

Input:
prices = [7,1,5,3,6,4]
Output:
7

Explanation: Buy at 1, sell at 5 (profit 4); buy at 3, sell at 6 (profit 3). Total profit = 4 + 3 = 7.

Example 2

Input:
prices = [1,2,3,4,5]
Output:
4

Explanation: Buy at 1, sell at 5 in one continuous climb — equivalent to summing every day-to-day gain: 1+1+1+1 = 4.

Example 3

Input:
prices = [7,6,4,3,1]
Output:
0

Explanation: Prices only fall, so no transaction is ever profitable.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Follow-up

What changes if a fixed transaction fee is charged on every sale?

Loading editor…

Code execution is coming soon.