The "Best Time to Buy and Sell Stock III interview question" increases the difficulty by adding a transaction limit. You are given an array of prices, but you may complete at most two transactions. Like before, you must sell the stock before you buy again. This constraint makes the simple greedy approach from the previous version unusable.
Companies like Goldman Sachs and Microsoft use the "Best Time to Buy and Sell Stock III coding problem" to test a candidate's mastery of Dynamic Programming. It requires the candidate to maintain multiple states (e.g., first buy, first sell, second buy, second sell) and update them in a single pass. It evaluates "Array interview pattern" and complex state-management skills.
This problem is solved using Dynamic Programming (State Machine). We maintain four variables representing the maximum balance at each stage:
first_buy: The most money you can have after buying the first stock. (Initially -prices[0]).first_sell: The most money you can have after selling the first stock.second_buy: The most money you can have after buying the second stock.second_sell: The most money you can have after selling the second stock.
For each price, we update these greedily:first_buy = max(first_buy, -price)first_sell = max(first_sell, first_buy + price)second_buy = max(second_buy, first_sell - price)second_sell = max(second_sell, second_buy + price)Prices: [3, 3, 5, 0, 0, 3, 1, 4]
first_buy = -3, first_sell = 2.first_buy = 0, first_sell = 2, second_buy = 2.first_sell = 3, second_buy = 2, second_sell = 5.second_sell = 6.
Total Max Profit: 6 (Transaction 1: buy at 0 sell at 3; Transaction 2: buy at 1 sell at 4).[0...i] and [i...n] for all is , which is too slow.max logic, the order within a single day often doesn't break the result).For problems with "at most K" actions, think about the state machine. Each action (buy/sell) moves you to a new state. This pattern is very common in "Dynamic Programming" interviews at high-frequency trading firms.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Best Time to Buy and Sell Stock IV | Hard | Solve | |
| Burst Balloons | Hard | Solve | |
| Minimum Difficulty of a Job Schedule | Hard | Solve | |
| Frog Jump | Hard | Solve | |
| Arithmetic Slices II - Subsequence | Hard | Solve |