Compute max profit with forced trades
Problem Description
Given an array prices where prices[i] represents the stock price on day i, you are required to solve two related tasks under specific "forced-trade" constraints.
Task A: Exactly One Transaction
Choose exactly one buy day and one later sell day to maximize profit. If prices never rise, you must still perform a transaction and return the least possible loss.
Task B: Exactly Two Transactions
Choose exactly two non-overlapping buy-sell pairs (meaning the first transaction's sell day must occur before the second transaction's buy day) to maximize total profit. If necessary, you must include losses to ensure exactly two transactions are performed.
Implementation Requirements
Implement two distinct functions, for example, profitExactlyOne(prices) and profitExactlyTwo(prices), to address Task A and Task B respectively.
Assumptions and Constraints
- Each transaction involves a single share.
- There are no transaction costs.
- Short selling is not permitted (i.e., you must buy before you sell).
- Handle edge cases gracefully, such as empty or single-element
pricesarrays. - No explicit time-complexity requirement is given, but efficient solutions are expected.
AI interview prep
Core dilemma
Adapting standard dynamic programming techniques to handle forced transactions and potential losses, ensuring global optimality across multiple, constrained subproblems.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Compute max profit with forced trades
Problem Description
Given an array prices where prices[i] represents the stock price on day i, you are required to solve two related tasks under specific "forced-trade" constraints.
Task A: Exactly One Transaction
Choose exactly one buy day and one later sell day to maximize profit. If prices never rise, you must still perform a transaction and return the least possible loss.
Task B: Exactly Two Transactions
Choose exactly two non-overlapping buy-sell pairs (meaning the first transaction's sell day must occur before the second transaction's buy day) to maximize total profit. If necessary, you must include losses to ensure exactly two transactions are performed.
Implementation Requirements
Implement two distinct functions, for example, profitExactlyOne(prices) and profitExactlyTwo(prices), to address Task A and Task B respectively.
Assumptions and Constraints
- Each transaction involves a single share.
- There are no transaction costs.
- Short selling is not permitted (i.e., you must buy before you sell).
- Handle edge cases gracefully, such as empty or single-element
pricesarrays. - No explicit time-complexity requirement is given, but efficient solutions are expected.