Max Profit From at Most K Trades of Cloud Spot Capacity
Last updated: November 29, 2026
Quick Overview
You trade one unit of spot compute capacity at known daily prices, hold at most one unit at a time, and may complete at most k buy-sell trades. Return the maximum profit.
0
0
0 solved
You trade one unit of spot compute capacity at known daily prices, hold at most one unit at a time, and may complete at most k buy-sell trades. Return the maximum profit.
A Google onsite hard that generalizes the stock state machine to a bounded number of transactions. Interviewers want the per-transaction state arrays, a correct update order, and the observation that large k reduces to the unlimited case.
What the Interviewer Expects
- Define buy[j] and sell[j] for the j-th transaction
- Update states in an order that uses yesterday's or same-day values safely
- Short-circuit when k >= n / 2
- Give O(n k) time and O(k) space
- Explain why same-day buy-then-sell does not break correctness
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Add a transaction fee.
- Return the actual trades.
- k is large and n is 10^5. Is there something faster than O(n k)?
- Allow holding up to two units.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: integer k >= 0 and list prices. A trade is a buy followed by a later sell; trades cannot overlap. Output the max profit using at most k trades. If k >= n // 2, k is no constraint because a pr...
High-Level Design
Let buy[j] be the best balance after the j-th buy so far, and sell[j] the best balance after the j-th sell. Each day p, for j from 1 to k: buy[j] = max(buy[j], sell[j-1] - p) and `sell[j] = max(...