Point72Best Time to Buy and Sell Stock II (LC 122) with Trade Report
LC 122 (unlimited transactions, hold at most one share). The data-engineering screen frames it as a 'Portfolio Trading Optimizer': write a `validate_prices` decorator for the stated constraints, a `find_transactions` that returns each buy/sell pair, and a `generate_report` that prints every trade plus total profit. The QR intern screen asks the plain version with complexity; a software screen used a k-transaction (LC 188-like) variant.
Problem
Given prices, where prices[i] is the stock price on day i, you may buy and/or sell on each day, holding at most one share at any time, and trade as many times as you like. Find the trades that maximize total profit.
In the data-engineering screen (30-minute coding half of a 1-hour screen), the starter file asks for three pieces:
#################################
## Portfolio Trading Optimizer ##
#################################
prices = [7, 1, 5, 3, 6, 4]
# prices constraints:
# length of prices between [0, 3*10^4]
# prices between [0, 10^4]
# prices non-negative integers
# Implement:
# 1. A decorator 'validate_prices' to validate input
# 2. A function 'find_transactions' to find the optimal trades
# 3. A function 'generate_report' to summarize the result
def validate_prices(func):
"""
write price validation based on the prices constraint
"""
@validate_prices
def find_transactions(prices):
"""
Input: prices list
Return: (buy_day, buy_price, sell_day, sell_prices, profit)
"""
def generate_report(prices):
"""
return something like this:
buy_day=1 buy_price=1 sell_day=2 sell_price=5 profit=4
buy_day=3 buy_price=3 sell_day=4 sell_price=6 profit=3
total_profit=7
"""Examples
prices = [7, 1, 5, 3, 6, 4]→ trades(1, 1, 2, 5, 4)and(3, 3, 4, 6, 3),total_profit=7(days are 0-indexed).
Variants
Plain algorithm question
The quant-research intern screen asks only the algorithm ("Best Time to Buy and Sell Stock II") and expects time and space complexity.
At most k transactions
A software-developer tech screen used a question similar to LC 188 (at most k transactions), followed by language-fundamentals questions.
Spec: maxProfit(k, prices) returns the maximum profit using at most k transactions, where one buy plus its sell counts as one transaction. Return 0 when len(prices) < 2 or k == 0.
Example: prices = [3,2,6,5,0,3], k = 2 → 7 (buy at 2, sell at 6 for 4; buy at 0, sell at 3 for 3).
Everything below tagged "k variant" refers to this version; the unscoped notes cover the main trade-report problem.
Hints
Pitfalls
- The decorator must enforce every stated constraint: list length 0 to 3*10^4 (an empty list is valid), values 0 to 10^4, non-negative integers only.
find_transactionsreturns trade tuples, not just a number, so a profit-only greedy is not enough; settle with the interviewer whether consecutive up-days are reported as one trade or several before writinggenerate_report.- Match the report format exactly (
key=valuepairs, one trade per line, trailingtotal_profit=line). - K variant: skipping the
k >= n // 2shortcut makes O(nk) blow up for hugek. - K variant: with one price per step, the order of the
buy[t]/sell[t]updates and the direction oftdo not change the answer (a same-day buy and sell nets zero). Initializingbuy[t]to0instead of-infdoes break it: it lets you sell a share you never bought.
Talking Points
For the k variant:
- Define the states exactly: "
buy[t]is the best profit aftert - 1completed transactions while in a buying position" beats a vague "profit after buying". - Call out
k >= n // 2explicitly: each transaction needs 2 days, so the effectivekis bounded byn // 2(for examplek = 10^9). - Trace
[3,2,6,5,0,3]withk = 2to show howbuyandsellevolve, rather than reciting code. - Explain why same-day buy-sell does not overcount: it has zero profit.
- Mention the space reduction from O(nk) to O(k): only the previous transaction count matters.
- Link the large-
kcase back to the unlimited-transactions greedy, which is the main problem.
Follow-ups
Preparation
- Write the three-function version from the starter file in under 20 minutes, including a decorator that raises on each constraint violation.
- Re-derive the O(N) greedy and state its complexity out loud.
- Solve the at-most-
k-transactions DP as well, since a software screen used that variant: write thebuy/sellversion from memory and trace[3,2,6,5,0,3],k = 2to7.
