Compute max profit with forced trades
RetoolSoftware Engineer · Technical ScreenLast updated
Compute max profit with forced trades evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Given an array prices where prices[i] is the stock price on day i, solve two related tasks under a forced-trade constraint: (a) Exactly one transaction: choose one buy day and one later sell day to maximize profit; if prices never rise, return the least possible loss that results from exactly one buy and one sell. (b) Exactly two transactions: choose two non-overlapping buy-sell pairs (sell before the next buy) to maximize total profit; if necessary, include losses so that exactly two transactions are performed. Implement two functions (e.g., profitExactlyOne(prices), profitExactlyTwo(prices)) and specify assumptions (single share per transaction; no transaction costs; cannot short). Handle edge cases (empty or single-element arrays). No explicit time-complexity requirement.
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.