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

Master LeetCode problem 714 (Best Time to Buy and Sell Stock with Transaction Fee), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

714. Best Time to Buy and Sell Stock with Transaction Fee

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will keep track of two states at each day: 1) the maximum profit we can have if we currently own a stock, and 2) the maximum profit we can have if we currently do not own a stock.

At each day, we update these two states based on the decisions of whether to buy, sell, or do nothing. We consider the transaction fee when buying or selling stocks.

The time complexity of this solution is O(n) where n is the number of days in the prices array. The space complexity is O(1) as we only need constant space to store the two states.

Solution Code

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int ownStock = -prices[0];
        int notOwnStock = 0;
        
        for (int i = 1; i < prices.length; i++) {
            int prevOwnStock = ownStock;
            int prevNotOwnStock = notOwnStock;
            
            // Decide whether to buy, sell, or do nothing
            ownStock = Math.max(prevOwnStock, prevNotOwnStock - prices[i]);
            notOwnStock = Math.max(prevNotOwnStock, prevOwnStock + prices[i] - fee);
        }
        
        return notOwnStock;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 714 (Best Time to Buy and Sell Stock with Transaction Fee)?

This page provides optimized solutions for LeetCode problem 714 (Best Time to Buy and Sell Stock with Transaction Fee) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

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

The time complexity for LeetCode 714 (Best Time to Buy and Sell Stock with Transaction Fee) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 714 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 714 in Java, C++, or Python.

Back to LeetCode Solutions