Leetcode 714: Best Time to Buy and Sell Stock with Transaction Fee

grid47
grid47
Exploring patterns and algorithms
Aug 27, 2024 6 min read

A stock price chart where the best time to buy and sell is highlighted, with the optimal prices softly glowing.
Solution to LeetCode 714: Best Time to Buy and Sell Stock with Transaction Fee Problem

You are given an array prices where prices[i] represents the price of a stock on the i-th day, and an integer fee that represents a transaction fee for each transaction. The task is to calculate the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `prices` of integers representing the prices of the stock for each day and an integer `fee` representing the transaction fee.
Example: prices = [2, 6, 4, 7, 5, 9], fee = 3
Constraints:
• 1 <= prices.length <= 5 * 10^4
• 1 <= prices[i] < 5 * 10^4
• 0 <= fee < 5 * 10^4
Output: Return the maximum profit that can be achieved after completing as many transactions as possible, where each transaction is subject to a transaction fee.
Example: 9
Constraints:
• The result should be a non-negative integer representing the maximum profit.
Goal: To compute the maximum profit by applying a dynamic programming approach.
Steps:
• Use two arrays, `buy` and `sell`, where `buy[i]` stores the maximum profit at day `i` when buying the stock, and `sell[i]` stores the maximum profit at day `i` when selling the stock.
• Initialize `buy[0]` as `-prices[0] - fee` since you can buy the stock on the first day with the fee applied.
• Iterate through the `prices` array, and for each day, compute the maximum profit from either holding the stock or selling it (while considering the transaction fee).
• Finally, the value in `sell[n-1]` will hold the maximum profit at the end of the array.
Goal: The solution should efficiently handle the constraints with large inputs up to `5 * 10^4` days.
Steps:
• The input array can have up to 50,000 elements.
• Each price in the array is between 1 and 50,000.
• The transaction fee is a non-negative integer less than 50,000.
Assumptions:
• The input array contains at least one price.
• The transaction fee is applied once for every transaction (buying and selling).
Input: prices = [2, 6, 4, 7, 5, 9], fee = 3
Explanation: The best strategy is to buy on day 1, sell on day 2, buy again on day 3, and sell on day 4. Then, buy on day 5 and sell on day 6. The total profit is 9.

Input: prices = [3, 2, 5, 1, 7], fee = 1
Explanation: The maximum profit can be obtained by buying at day 2 and selling at day 3, and then buying at day 4 and selling at day 5. The total profit is 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus