![]() |
VOOZH | about |
Given an array arr[] denoting the cost of stock on each day and an integer k representing a transaction fee. Find the maximum total profit if we can buy and sell the stocks any number of times given that each transaction costs fee k.
Note: We can only sell a stock which we have bought earlier and we cannot hold multiple stocks on any day.
Examples:
Input: arr[] = [6, 1, 7, 2, 8, 4], k = 2
Output: 8
Explanation:
Buy the stock on day 2 and sell it on day 3 => 7 – 1 -2 = 4
Buy the stock on day 4 and sell it on day 5 => 8 – 2 - 2 = 4
Maximum Profit = 4 + 4 = 8Input: arr[] = [7, 1, 5, 3, 6, 4], k = 1
Output: 5
Explanation:
Buy the stock on day 2 and sell it on day 3 => 5 – 1 - 1 = 3
Buy the stock on day 4 and sell it on day 5 => 6 – 3 - 1 = 2
Maximum Profit = 3 + 2 = 5
Table of Content
The idea is to recursively generate all possible buy and sell combinations and compute the maximum among them. To do so, create a counter buy, which is 0 if no stock has been purchased else it is 1. Start from the 0th index, and for each index i, there are two possibilities:
- buy == 0: If no stock has been purchased, we can either skip the stock arr[i], or can purchase it by subtracting arr[i] from profit.
- buy == 1: If a stock has been purchased, we can't buy more and need to sell it. We can either sell it in current rate by adding arr[i] to profit and subtracting k of transaction fee, or skip to the next stock.
The maximum of this is the result.
8
The above approach can be optimized using memoization. The idea is to create a 2d array memo[][] of order n*2, where element memo[i][0] stores the maximum profit from day i to n-1 when no previous stock is pending and memo[i][1] stores maximum profit from day i to n-1 when there is previous stock remaining. For each recursive call, check if the sub-array is already computed, if so return the stored value else proceed as in above approach.
8
The idea is to use tabulation (bottom-up DP) approach and build the solution iteratively.
We create a 2D array dp[n + 1][2], where:
We fill this table in a bottom-up manner, starting from the last day and moving backward.
For each day i:
- If we can buy (buy == 0): We have two options — buy the stock and subtract its price from profit, or skip to the next day.
dp[i][0] = max(-arr[i] + dp[i + 1][1], dp[i + 1][0])- If we can sell (buy == 1): We can either sell the stock (add price to profit and subtract transaction fee k) or skip to the next day.
dp[i][1] = max(arr[i] - k + dp[i + 1][0], dp[i + 1][1])The base case is when we reach beyond the last index — profit is 0.
Finally, dp[0][0] gives the maximum profit possible starting from day 0 with the ability to buy.
8
Instead of using a DP table, we observe that each day’s profit depends only on the next day’s states.
So, we keep two variables:
For each day (starting from the end):
Update both states for the next iteration. Finally, noStock holds the maximum achievable profit.
8