FunctionRacerProblemsRace

Two Trades at Most

HardArraysPython, JavaScript, TypeScript, Java, C++

prices[i] is the price of one share on day i. A trade buys one share on some day and sells it on a later day, earning the difference. You may make at most two trades, and you never hold more than one share: the second share may be bought only on the day the first one is sold or later.

Return the largest total profit you can make. If no trade earns anything (or prices has fewer than two days), return 0.

Example 1

prices [3,3,5,0,0,3,1,4]
returns 6

Buy at 0 on day 3 and sell at 3 on day 5 for 3, then buy at 1 on day 6 and sell at 4 on day 7 for 3 more.

Example 2

prices [1,2,3,4,5]
returns 4

Prices only rise, so one trade from 1 to 5 earns 4; splitting it into two trades cannot earn more.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Arrays problems