Algo-Sim › Dynamic Programming
Best Time to Buy and Sell Stock with Transaction Fee
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Trade as often as you like, paying a fee per trade. Two states per day, hold and free, with the fee on the sell arrow.
Problem
You are given prices, where prices[i] is the price of a stock on day i, and a fee paid on every completed transaction. You may buy and sell as many times as you like, but hold at most one share at a time. Return the maximum profit.
Constraints
- 1 ≤ prices.length ≤ 5 · 10⁴
- 1 ≤ prices[i] < 5 · 10⁴
- 0 ≤ fee < 5 · 10⁴
- At most one share at a time
Edge cases to test
- A fee larger than every rise:
0 - Fee 0: the same as Stock II
- One day
Follow-up questions
- Does it matter where the fee is paid?
- No: on the buy or on the sell gives the same answer, as long as it is paid once per trade.
- Why not just sum the rises above the fee?
- Holding through a small dip can avoid paying the fee twice; the two-state DP decides that.
Solution
Java
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int[] hold = new int[n], free = new int[n];
hold[0] = -prices[0];
for (int i = 1; i < n; i++) {
hold[i] = Math.max(hold[i - 1], free[i - 1] - prices[i]);
free[i] = Math.max(free[i - 1], hold[i - 1] + prices[i] - fee);
}
return free[n - 1];
}Python
def max_profit(prices, fee):
n = len(prices)
hold, free = [0] * n, [0] * n
hold[0] = -prices[0]
for i in range(1, n):
hold[i] = max(hold[i - 1], free[i - 1] - prices[i])
free[i] = max(free[i - 1], hold[i - 1] + prices[i] - fee)
return free[n - 1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices, int fee) {
int n = int(prices.size());
vector<int> hold(n), free(n);
hold[0] = -prices[0];
for (int i = 1; i < n; i++) {
hold[i] = max(hold[i - 1], free[i - 1] - prices[i]);
free[i] = max(free[i - 1], hold[i - 1] + prices[i] - fee);
}
return free[n - 1];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)