Similar Problems

Similar Problems not available

Best Time To Buy And Sell Stock With Transaction Fee - Leetcode Solution

Companies:

LeetCode:  Best Time To Buy And Sell Stock With Transaction Fee Leetcode Solution

Difficulty: Medium

Topics: greedy dynamic-programming array  

Problem Statement: You are given an array of integers prices, for which the ith element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock before you buy again).

Return the maximum profit you can make.

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

  • Buying at prices[0] = 1
  • Selling at prices[3] = 8
  • Buying at prices[4] = 4
  • Selling at prices[5] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note: 0 < prices.length <= 50000. 0 < prices[i] < 50000. 0 < fee < 50000.

Approach: We use the Dynamic Programming approach to solve this problem. Let dp[i][0/1] be the maximum profit that can be obtained if we end up ith day with 0 shares / 1 share. Initially, at day 0, dp[0][0] = 0 and dp[0][1] = -prices[0]. We then move onto day 1 and follow the following cases:

  • If we have 0 shares at the beginning of the day, we can either choose to do nothing or buy the share. The maximum profit in such a case is either the profit that can be made by doing nothing (ie. dp[i-1][0]), or the profit that can be made if we buy the share (i.e., dp[i-1][1] - prices[i]). Here we subtract the current price as we buy the share.
  • If we have 1 share at the beginning of the day, we can either choose to do nothing, sell the share, or skip this day. The maximum profit in such cases are:
    • If we do nothing, our profit remains the same and is given by dp[i-1][1].
    • If we sell the share, our profit is given by dp[i-1][1] + prices[i] - fee as we have to pay the transaction fee.
    • If we skip this day, our profit remains the same and is given by dp[i-1][1].
  • After day n, we return dp[n][0], as profit with zero shares will always be greater than the profit with one share.

Code:

class Solution { public: int maxProfit(vector<int>& prices, int fee) { int n = prices.size(); int dp[n][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for(int i=1;i<n;i++) { dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i] - fee); dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); } return dp[n-1][0]; } };

Time Complexity: The time complexity of the above solution is O(n), where n is the length of the prices array as we traverse through the array only once.

Space Complexity: The space complexity of the above solution is O(n) as we declare a 2D array of size n.

Best Time To Buy And Sell Stock With Transaction Fee Solution Code

1