Best Time to Buy and Sell Stock with Transaction Fee

Given an array of integers A of size N in which ith element is the price of the stock on day i,

You may complete as many transactions
as you like (ie, buy one and sell one share of the stock multiple times)
but you need to pay the transaction fee B for each transaction.

Find the maximum profit you can achieve.

Note: You may not buy more than 1 share of a stock at a time (i.e. you must sell the stock share before you buy again.)



Input Format

The First argument given is the integer array A.
The Second argumnet is an integer B.

Output Format

Return the maximum profit you can achieve.

Constraints

1 <= N <= 50000
0 <= A[i] <= 50000
0 <= B <= 50000

For Example

Input 1:
    A = [1, 3, 2, 8, 4, 9]
    B = 2
Output 1:
    8
    Explanation 1:
        Buying at A[0] = 1
        Selling at A[3] = 8
        Buying at A[4] = 4
        Selling at A[5] = 9
        The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Input 2:
    A = [1, 2, 3, 1]
    B = 0
Output 2:
    2
    Explanation 2:
        Buying at A[0] = 1
        Selling at A[2] = 8
        The total profit is ((3 - 1) - 0) = 2.
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Best Time to Buy and Sell Stock with Transaction Fee on Interview Code Editor
Sign Up
to access hints and editorial solutions for Best Time to Buy and Sell Stock with Transaction Fee

Discussion


Loading...
Click here to start solving coding interview questions