MediumNo. 0714

Best Time to Buy and Sell Stock with Transaction Fee — LeetCode 714 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Dynamic Programming
On a study list
LeetCode 75
Reading time
3 min

The problem

You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee. Find the maximum profit you can achieve.

Example

Input
prices = [1,3,2,8,4,9], fee = 2
Output
8
Explanation
The maximum profit can be achieved by:

Python solution

PythonSolution
class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i >= len(prices):
                return 0
            ans = dfs(i + 1, j)
            if j:
                ans = max(ans, prices[i] + dfs(i + 1, 0) - fee)
            else:
                ans = max(ans, -prices[i] + dfs(i + 1, 1))
            return ans

        return dfs(0, 0)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0121Best Time to Buy and Sell StockEasy
0045Jump Game IIMedium
0055Jump GameMedium
0122Best Time to Buy and Sell Stock IIMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium

Frequently asked questions

How hard is LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee?

LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee is rated Medium on LeetCode.

What is the time complexity of LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee cover?

LeetCode 714. Best Time to Buy and Sell Stock with Transaction Fee is tagged Greedy, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.