#3573

Best Time to Buy and Sell Stock V

specialist · 715 · lc medium +30 · 60.8% accepted · 415 likes · top 60%

Description

An integer array prices gives the stock price on each day, and k limits the total transactions allowed.

Each transaction is one of:

- Long trade: buy on day i, sell on a later day j (i < j), profiting prices[j] - prices[i].

- Short trade: sell on day i, buy back on a later day j (i < j), profiting prices[i] - prices[j].

Each transaction must be fully closed before opening another. The closing day of one transaction and the opening day of the next cannot overlap.

Return the maximum cumulative profit achievable with at most k transactions.

Code

1
2
3