Maximum Profit from Stock Trades

Coding · Easy · Free problem
You are given an array `prices` of length $n$ where `prices[i]` is the price of a stock on day $i$. Solve two versions: **Part 1 -- Single Transaction:** You may buy once and sell once (buy before sell). Find the maximum profit. If no profit is possible, return 0. **Part 2 -- Unlimited Transactions:** You may buy and sell as many times as you like (but you must sell before buying again). Find the maximum total profit. **Constraints:** -
\leq n \leq 10^5$ - $0 \leq$ `prices[i]` $\leq 10^4$ **Examples:** Part 1: - Input: `[7, 1, 5, 3, 6, 4]` -> Output: `5` (buy at 1, sell at 6) - Input: `[7, 6, 4, 3, 1]` -> Output: `0` (prices only decrease, no profit possible) Part 2: - Input: `[7, 1, 5, 3, 6, 4]` -> Output: `7` (buy at 1, sell at 5: profit 4; buy at 3, sell at 6: profit 3) - Input: `[1, 2, 3, 4, 5]` -> Output: `4` (buy at 1, sell at 5; equivalent to capturing every upward move)

Open the full interactive solver, hints, and worked solution →