Unify Stock-Trading Profit Variants
AmazonSoftware Engineer · Technical ScreenLast updated
This problem tests state-space dynamic programming by unifying different stock trading constraints (transaction limits and per-transaction fees) into a single optimized state-transition model.
Problem Statement
You are tasked with designing a unified stock-trading profit calculator. You are given an array prices where prices[i] is the price of a stock on the i-th day, an integer k representing the maximum number of transactions allowed, and a float fee representing a per-transaction cost (incurred at the time of sale).
Implement the following interface:
def max_profit(prices: list[int], k: int, fee: float) -> float:
pass
Rules:
- You may engage in at most
ktransactions (buy then sell). - You must sell the stock before you can buy again.
- You cannot engage in multiple transactions simultaneously.
- A transaction is defined as a buy followed by a sale; the
feeis subtracted from the profit only upon the sale.
Constraints:
1 <= prices.length <= 10^40 <= prices[i] <= 10^50 <= k <= 10^90 <= fee <= 10^5
Examples:
Example 1:
- Input:
prices = [1, 3, 2, 8, 4, 9], k = 2, fee = 2 - Output:
8.0 - Explanation: Buy at 1, sell at 8 (profit 7 - 2 fee = 5). Buy at 4, sell at 9 (profit 5 - 2 fee = 3). Total = 8.
Example 2:
- Input:
prices = [1, 2], k = 10^9, fee = 0 - Output:
1.0 - Explanation: Unlimited transactions allowed, no fee.
Hints
Hint 1
Define a DP state based on two variables: the current day and the number of transactions completed, while tracking whether you currently hold a stock.
Hint 2
Observe that if `k` is very large (e.g., `k >= len(prices) / 2`), the constraint effectively becomes unlimited transactions.
Hint 3
For the finite `k` case, maintain two arrays representing the maximum cash in hand and maximum stock value held for each transaction count up to `k`.
Follow-up questions
- How does your algorithm change if you add a 'cooldown' period of 1 day after every sale?
- If `k` is extremely large, can you optimize the space complexity to O(1) instead of O(k)?
- How would you modify this to account for short-selling (selling before buying) if the platform allowed it?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.