Ctrl K

Profit From Two Trades

Hard
You know the price of a coin for the coming days: rates[i] is its price on day i. A trade is buying the coin and selling it later. You can hold at most one coin at a time, so a new purchase is only possible after the previous coin is sold (the same day is fine). You may make at most two trades. Return the largest total profit; if no profit is possible, return 0.
Example 1
rates=[4, 9, 2, 2, 7, 1, 6] → 10

Buy at 4, sell at 9 (+5); buy at 2, sell at 7 (+5). That is 10 in total; a third trade (1 → 6) is not allowed.

Example 2
rates=[1, 3, 5, 8] → 7

One trade 1 → 8 earns 7, more than any two trades.

Example 3
rates=[9, 6, 6, 2] → 0

The price only falls, so the best move is to do nothing: 0.

Constraints
  • 1 ≤ len(rates) ≤ 10⁵
  • 0 ≤ rates[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardBiggest Solid Panel Block HardEvery Way to Space the Words HardCrossing the Cave HardProfit With a Limited Number of Trades Hard
loading Python…
Input
rates=[4, 9, 2, 2, 7, 1, 6]
Expected
10

Run checks the first 3 tests in your browser. Submit checks all 120 tests on the server, hidden ones included.