You are given an array 'prices' of size 'n', denoting the price of stocks on 'n' days.
Rahul can buy one stock at a time, and he must sell it before buying stock on another day.
The entire transaction of selling and buying the stock requires some transaction fee, given as 'fee'.
Find the maximum profit Rahul can achieve by trading on the stocks.
Input: 'prices' = [1, 2, 3] and 'fee' = 1
Output: 1
Explanation: We can generate the maximum profit of 1 by buying the stock on the first day for price = 1 and then selling it on the third day for price = 3.
The profit will be: 3 - 1 - 1(transaction fee) = 1
The first line contains integers 'n' and 'fee' denoting the number of days and the transaction fee.
The second line contains 'n' integers, denoting the price of stocks on each day.
Print the maximum profit Rahul can achieve by trading on the stocks.
You do not need to print anything; it has already been taken care of. Just implement the given function.
3 1
1 2 3
1
We can generate the maximum profit of 1 by buying the stock on the first day for price = 1 and then selling it on the third day for price = 3.
The profit will be: 3 - 1 - 1(transaction fee) = 1
4 2
1 3 5 6
3
The expected time complexity is O(n).
1 <= 'n' <= 10 ^ 4
0 <= 'prices[i]' <= 10 ^ 5
0 <= 'fee'<= 10 ^ 5
Try solving using Dynamic Programming.
Let dp[i][status] be the maximum profit in the first i days when:
'status' = 0 means we are not having any stock on the i-th day.
'status' = 1 means we are having a stock on the i-th day.
Every day, we have 2 choices:
If we have a stock, either sell it or not.
If we don't have stock, either buy it or not.
Depending on these, we will write our transitions.
Our final answer will be dp[n][0] because this the the maximum profit after 'n' days and not having any stock with us.
Algorithm:
O(n), where 'n' is the size of the array 'prices'
As we are iterating over the array running the loop 'n' times, the time complexity will be O(n).
O(n), where 'n' is the size of the array 'prices'
As we are creating a matrix of dimensions ('n' + 1) * 2, the space complexity will be O(n).