Doraemon aims to make a fortune from the significant daily price changes of dorayakis. He plans to buy a dorayaki on one day and sell it on another to profit from the price spread. To keep his plan secret, Doraemon will only hold one dorayaki at a time, meaning he must sell each one before buying another.
Given the dorayaki prices over a continuous span of N days, please calculate the maximum profit Doraemon can gain.
(This part differs from the Practice Problem "Doraemon's dorayaki")
Recently, Doraemon decided not to be too ostentatious (炫耀的) for this evil plan and chose to limit the number of transactions he can make (where a 'transaction' is defined as buying and selling one dorayaki). In this problem, an integer M is given to restrict Doraemon to do at most M transactions. If M equals -1, this means that there is still no limit to the number of transactions.
N = 8 days, M = unlimited transactions (-1), prices = [7, 2, 5, 6, 3, 8, 1, 9]
Buy on day 2 (-2) -> Sell on day 4 (+6) -> Buy on day 5 (-3) -> Sell on day 6 (+8) -> Buy on day 7 (-1) -> Sell on day 8 (+9)
Maximum profit = (-2) + 6 + (-3) + 8 + (-1) + 9 = 17
N = 8 days, M = 1 transaction, prices = [7, 2, 5, 6, 3, 8, 1, 9]
Buy on day 7 (-1) -> Sell on day 8 (+9)
Maximum profit = (-1) + 9 = 8
N = 8 days, M = 2 transactions, prices = [7, 2, 5, 6, 3, 8, 1, 9]
Buy on day 2 (-2) -> Sell on day 6 (+8) -> Buy on day 7 (-1) -> Sell on day 8 (+9)
Maximum profit = (-2) + 8 + (-1) + 9 = 14
Output a single line containing one integer — the maximum profit Doraemon can gain.