Hone logo
Hone
Problems

Best Time to Buy and Sell Stock III

This problem challenges you to maximize your profit by performing at most two transactions on a given stock price history. Understanding dynamic programming and keeping track of optimal buy and sell points across multiple transactions is key to solving this efficiently. This is a common interview question that tests your ability to optimize solutions for maximum profit.

Problem Description

You are given an array prices where prices[i] is the price of a given stock on the i-th day. You are allowed to complete at most two transactions (i.e., buy one stock and sell it, buy another stock and sell it). You may buy and sell the stock on the same day.

Your goal is to find the maximum profit you can achieve.

Requirements:

  • You must return the maximum profit achievable with at most two transactions.
  • If no profit can be made, return 0.
  • You cannot short sell the stock (i.e., you must buy before you sell).

Expected Behavior:

The function should take an array of integers prices as input and return an integer representing the maximum profit. The function should handle empty or single-element arrays gracefully, returning 0 in those cases.

Edge Cases to Consider:

  • Empty input array: Should return 0.
  • Single-element input array: Should return 0.
  • Prices are consistently decreasing: Should return 0.
  • Large price fluctuations: Should correctly identify the optimal buy and sell points for two transactions.

Examples

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

Input: prices = [1]
Output: 0
Explanation: Single element array, no transactions possible.

Constraints

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

Notes

Consider using dynamic programming to efficiently track the maximum profit achievable up to each day for one transaction, and then for two transactions. You can use two arrays to store the maximum profit achievable with one transaction ending on each day, and the maximum profit achievable with two transactions ending on each day. Think about how to build these arrays iteratively, considering the best buy and sell points encountered so far. The final result will be the maximum value in the two-transaction array.

Loading editor...
plaintext