← 返回 optiver 的题目列表Thread-safe Stock Buy/Sell API Preventing Oversell
类型:online_judge
Implement two functions buy(symbol, qty) and sell(symbol, qty) to maintain stock positions, and ensure that under concurrent multi-threaded calls the system never oversells.
Requirements
Maintain the current position (share count) for each symbol (initially 0).
buy(symbol, qty): increase the position by qty.
sell(symbol, qty): decrease the position by qty, but must guarantee:
The position can never go below 0 at any time (no overselling).
If the current position is less than qty, the call must fail (e.g., return False, throw an exception, or return an error code—choose one and keep it consistent).
Concurrency
buy/sell may be called by multiple threads concurrently.
Use locks (mutex) or an equivalent synchronization mechanism so that the check-and-update is atomic.
I/O contract (you may choose and fix one)
symbol is a string.
qty is a positive integer.
Return value should indicate success or failure.
Scale & edge cases
Multiple symbols may exist.
Correctness under high contention is required.
Example (logical)
Start: AAPL = 0
After buy("AAPL", 10): AAPL = 10
If two threads call sell("AAPL", 7) concurrently, only one can succeed (or at most one such that the position never becomes negative), and the position must never drop below 0.
Example
Input
N/A (API design question; consider two threads both calling sell('AAPL', 7) after buy('AAPL', 10))
Output
At most one sell succeeds; final AAPL position is either 3 (one success) or 10 (zero success), never negative.