All problems

Problem 311

Stock Trading with Transaction Fee

Medium · 20 pts · Array, Dynamic Programming, Greedy

Problem

You are given the price of a stock for each of N days and a fee F. You may buy and sell as many times as you like, but you can hold at most one share at a time, so you must sell before buying again. Every completed transaction (a buy followed by a sell) costs the fee F once. Find the maximum total profit. Doing nothing at all gives a profit of 0.

Input

The first line contains N and F. The second line contains N prices.

Output

Print the maximum profit.

Constraints

1 <= N <= 100000; 0 <= F <= 50000; 1 <= price <= 50000

Example input

6 2
1 3 2 8 4 9

Example output

8

Explanation

With fee 2 and prices 1 3 2 8 4 9: buy at 1 and sell at 8 (profit 7 - 2 = 5), then buy at 4 and sell at 9 (profit 5 - 2 = 3). The total is 8, which is the best possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Majority Element II Next: Minimum Swaps to Sort