Practice Problem

Best Time to Buy and Sell Stock II

Difficulty: Medium

Given an array of daily stock prices, find the maximum profit you can achieve with unlimited buy-sell transactions (one share at a time).

Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or 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.

Find and return the maximum profit you can achieve.

Examples

Example 1:

Input: prices = [7, 1, 5, 3, 6, 4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4.
  Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3.
  Total profit = 4 + 3 = 7.
  Note: Buying on day 2 and selling on day 5 is not allowed because you
  must sell before you buy again.

Example 2:

Input: prices = [1, 2, 3, 4, 5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5),
  profit = 4. This is equivalent to buying/selling on consecutive days:
  (2-1) + (3-2) + (4-3) + (5-4) = 4.

Example 3:

Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices only decrease. No profitable transaction is possible.

Constraints

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

Expected Complexity

  • Time: O(n)
  • Space: O(1)
MEDIUM
Greedy
Arrays
Algorithms
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium