Hone logo
Hone
Problems

Best Time to Buy and Sell Stock II

This problem challenges you to maximize your profit by buying and selling a stock multiple times. Unlike the "Best Time to Buy and Sell Stock I" problem, you are allowed to complete as many transactions as you like, as long as you sell a stock before you buy it again. This is a common problem in algorithmic trading and demonstrates a simple strategy for profit maximization.

Problem Description

You are given an array prices where prices[i] is the price of a given stock on the i-th day. Your task is to calculate the maximum profit you can make by buying and selling the stock multiple times. You must sell the stock before you buy it again.

What needs to be achieved:

  • Determine the maximum profit achievable by buying and selling the stock zero or more times.
  • The profit for a single transaction is the difference between the selling price and the buying price.
  • You must buy before you sell.

Key Requirements:

  • The input is an array of integers representing the stock prices for each day.
  • You can buy and sell the stock on the same day (though this won't typically be profitable).
  • You cannot buy the stock again until you have sold it.

Expected Behavior:

The function should return an integer representing the maximum profit. If no profit can be made (e.g., prices are always decreasing), the function should return 0.

Edge Cases to Consider:

  • Empty input array: Should return 0.
  • Array with only one element: Should return 0.
  • Prices always decreasing: Should return 0.
  • Prices always increasing: Should return the total difference between the last and first price.

Examples

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4. Buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3. Total profit = 4 + 3 = 7.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: No profitable transactions can be made.

Constraints

  • 1 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000
  • The input array prices will only contain positive integers.
  • The solution should have a time complexity of O(n), where n is the length of the prices array.

Notes

A simple and efficient approach is to iterate through the prices array and accumulate the profit whenever the price increases from one day to the next. Focus on identifying upward trends and capitalizing on them. You don't need to track individual buy and sell days; just the cumulative profit. Consider how you can identify profitable transactions without storing the buy and sell days themselves.

Loading editor...
plaintext