Open In App

Maximum profit after buying and selling stocks with transaction fees

Last Updated : 31 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of positive integers containing the price of stocks and transaction fee, the task is to find the maximum profit and the difference of days on which you are getting the maximum profit. 

Examples: 

Input: arr[] = {6, 1, 7, 2, 8, 4}
      transactionFee = 2
Output: 8 1

Input: arr[] = {7, 1, 5, 3, 6, 4}
       transactionFee = 1
Output: 5 1

Explanation: Considering the first example: arr[] = {6, 1, 7, 2, 8, 4}, transactionFee = 2 

  1. If we buy and sell on the same day, we will not get any profit that’s why the difference between the buying and selling must be at least 1.
  2. With the difference of 1 day, if we buy a stock of rupees 1 and sell it rupees 7 with the difference of day 1 which mean purchase on day 2 and sell it next day,then after paying the transaction fee of rupees 2 i.e. 7-1-2=4, we will get profit of 4 rupees, same as if we purchase on day 4 and sell it on day 5 with the difference of day 1 then we get profit of 4 rupees. So the total profit is 8 rupees.
  3. With the difference of 2 days, we will not get any profit.
  4. With the difference of 3 days, if we buy stock of rupees 1 and sell it rupees 8 with the difference of 3 days which mean purchase on day 2 and sell it after 3 days then maximum profit after paying the transaction fee of rupees 2 i.e.8-1-2=5 we will get the profit of 5 rupees.
  5. With the difference of 4 days, if we buy stocks of rupees 1 and sell it rupees 4 with the difference of 4 days which mean purchase on day 2 and sell it after 4 days then after paying the transaction fee of rupees 2 i.e. 4-1-2=1, we will get profit of 1 rupees.
  6. With the difference of 5 days, we will not get any profit.

Approach: 

  1. Traverse the whole array with the difference of each day.
  2. Check the profit by subtracting the price of each day including transaction fee.
  3. Trace the maximum profit and store the diff_days on which we are getting the maximum profit.
  4. Repeat the above steps until the loop terminates.

Below is the implementation of above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
int max_profit(int a[], int b[], int n, int fee)
{
    int i, j, profit;
    int l, r, diff_day = 1, sum = 0;
    // b[0] will contain the maximum profit
    b[0] = 0;
    // b[1] will contain the day on which we are getting the
    // maximum profit
    b[1] = diff_day;
    for (i = 1; i < n; i++) {
        l = 0;
        r = diff_day;
        sum = 0;
 
        for (j = n - 1; j >= i; j--) {
            // here finding the max profit
            profit = (a[r] - a[l]) - fee;
 
            // if we get less then or equal to zero it means
            // we are not getting the profit
            if (profit > 0)
                sum = sum + profit;
            l++;
            r++;
        }
        // check if sum is greater then maximum then store
        // the new maximum
        if (b[0] < sum) {
            b[0] = sum;
            b[1] = diff_day;
        }
        diff_day++;
    }
    return 0;
}
 
// Driver code
int main()
{
    int arr[] = { 6, 1, 7, 2, 8, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int b[2];
    int tranFee = 2;
    max_profit(arr, b, n, tranFee);
    cout << b[0] << ", " << b[1] << endl;
    return 0;
}


C




// C implementation of above approach
#include <stdio.h>
 
int max_profit(int a[], int b[], int n, int fee)
{
    int i, j, profit;
    int l, r, diff_day = 1, sum = 0;
    // b[0] will contain the maximum profit
    b[0] = 0;
    // b[1] will contain the day on which we are getting the
    // maximum profit
    b[1] = diff_day;
    for (i = 1; i < n; i++) {
        l = 0;
        r = diff_day;
        sum = 0;
 
        for (j = n - 1; j >= i; j--) {
            // here finding the max profit
            profit = (a[r] - a[l]) - fee;
 
            // if we get less then or equal to zero it means
            // we are not getting the profit
            if (profit > 0)
                sum = sum + profit;
            l++;
            r++;
        }
        // check if sum is greater then maximum then store
        // the new maximum
        if (b[0] < sum) {
            b[0] = sum;
            b[1] = diff_day;
        }
        diff_day++;
    }
    return 0;
}
 
// Driver code
int main()
{
    int arr[] = { 6, 1, 7, 2, 8, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int b[2];
    int tranFee = 2;
    max_profit(arr, b, n, tranFee);
    printf("%d, %d", b[0], b[1]);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta


Java




// Java implementation of above approach
import java.util.*;
 
class solution
{
 
static int max_profit(int a[],int b[],int n,int fee)
{
int i, j, profit;
 
int l, r, diff_day = 1, sum = 0;
 
//b[0] will contain the maximum profit
    b[0]=0;                
//b[1] will contain the day
//on which we are getting the maximum profit
    b[1]=diff_day;
for(i=1;i<n;i++)
{
    l=0;
    r=diff_day;
        sum=0;    
 
    for(j=n-1;j>=i;j--)
        {
        //here finding the max profit
            profit=(a[r]-a[l])-fee;
     
        //if we get less then or equal to zero
        // it means we are not getting the profit
            if(profit>0)    
                {
                sum=sum+profit;
                }
            l++;
     
            r++;
            }
//check if sum is greater then maximum then store the new maximum
    if(b[0] < sum)
{
    b[0] = sum;
     
    b[1] = diff_day;
 
    }
diff_day++;
}
 
return 0;
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 6, 1, 7, 2, 8, 4 };
    int n = arr.length;
    int[] b = new int[2];
    int tranFee = 2;
 
    max_profit(arr, b, n, tranFee);
 
    System.out.println(b[0]+", "+b[1]);
 
}
}
 
//This code is contributed by Surendra_Gangwar


Python3




# Python3 implementation of above approach
def max_profit(a, b, n, fee):
 
    i, j, profit = 1, n - 1, 0
     
    l, r, diff_day = 0, 0, 1
     
    # b[0] will contain the maximum profit
    b[0] = 0   
     
    # b[1] will contain the day on which
    # we are getting the maximum profit
    b[1] = diff_day
 
    for i in range(1, n):
        l = 0
        r = diff_day
        Sum = 0
     
        for j in range(n - 1, i - 1, -1):
             
            # here finding the max profit
            profit = (a[r] - a[l]) - fee
         
            # if we get less then or equal to zero
            # it means we are not getting the profit
            if(profit > 0):
                Sum = Sum + profit
                     
            l += 1
            r += 1
                 
        # check if Sum is greater then maximum
        # then store the new maximum
        if(b[0] < Sum):
            b[0] = Sum
            b[1] = diff_day
     
    diff_day += 1
     
    return 0
     
# Driver code
arr = [6, 1, 7, 2, 8, 4]
n = len(arr)
b = [0 for i in range(2)]
tranFee = 2
 
max_profit(arr, b, n, tranFee)
 
print(b[0], ",", b[1])
 
# This code is contributed by
# Mohit kumar 29


C#




// C# implementation of above approach
using System;
 
class GFG
{
     
static int max_profit(int []a, int []b,
                      int n, int fee)
{
int i, j, profit;
 
int l, r, diff_day = 1, sum = 0;
 
// b[0] will contain the
// maximum profit
b[0] = 0;
 
// b[1] will contain the day on which
// we are getting the maximum profit
b[1] = diff_day;
for(i = 1; i < n; i++)
{
    l = 0; r = diff_day; sum = 0;
 
    for(j = n - 1; j >= i; j--)
        {
            // here finding the max profit
            profit = (a[r] - a[l]) - fee;
     
            // if we get less then or equal
            // to zero it means we are not
            // getting the profit
            if(profit > 0)
            {
                sum = sum + profit;
            }
            l++;
     
            r++;
        }
         
    // check if sum is greater then maximum
    // then store the new maximum
    if(b[0] < sum)
    {
        b[0] = sum;
         
        b[1] = diff_day;
     
    }
    diff_day++;
}
 
return 0;
}
 
// Driver code
static public void Main ()
{
    int []arr = { 6, 1, 7, 2, 8, 4 };
    int n = arr.Length;
    int[] b = new int[2];
    int tranFee = 2;
     
    max_profit(arr, b, n, tranFee);
     
    Console.WriteLine(b[0] + ", " + b[1]);
}
}
 
// This code is contributed by Sachin


PHP




<?php
// PHP implementation of above approach
 
function max_profit(&$a, &$b, $n, $fee)
{
    $diff_day = 1;
    $sum = 0;
     
    // b[0] will contain the maximum profit
    $b[0] = 0;
     
    // b[1] will contain the day on which we
    // are getting the maximum profit
    $b[1] = $diff_day;
     
    for($i = 1; $i < $n; $i++)
    {
        $l = 0;
        $r = $diff_day;
        $sum = 0;
     
        for($j = $n - 1; $j >= $i; $j--)
        {
            // here finding the max profit
            $profit = ($a[$r] - $a[$l]) - $fee;
     
            // if we get less then or equal to zero
            // it means we are not getting the profit
            if($profit > 0)    
            {
                $sum = $sum + $profit;
            }
            $l++;
     
            $r++;
        }
         
        // check if sum is greater then maximum
        // then store the new maximum
        if($b[0] < $sum)
        {
            $b[0] = $sum;
             
            $b[1] = $diff_day;
        }
        $diff_day++;
    }
 
}
 
// Driver code
$arr = array(6, 1, 7, 2, 8, 4 );
$n = sizeof($arr);
$b = array();
$tranFee = 2;
 
max_profit($arr, $b, $n, $tranFee);
echo($b[0]);
echo(", ");
echo($b[1]);
 
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript




<script>
 
// Javascript implementation of above approach
 
    function max_profit(a , b , n , fee) {
        var i, j, profit;
 
        var l, r, diff_day = 1, sum = 0;
 
        // b[0] will contain the maximum profit
        b[0] = 0;
        // b[1] will contain the day
        // on which we are getting the maximum profit
        b[1] = diff_day;
        for (i = 1; i < n; i++) {
            l = 0;
            r = diff_day;
            sum = 0;
 
            for (j = n - 1; j >= i; j--) {
                // here finding the max profit
                profit = (a[r] - a[l]) - fee;
 
                // if we get less then or equal to zero
                // it means we are not getting the profit
                if (profit > 0) {
                    sum = sum + profit;
                }
                l++;
 
                r++;
            }
            // check if sum is greater then maximum
            // then store the new maximum
            if (b[0] < sum) {
                b[0] = sum;
 
                b[1] = diff_day;
 
            }
            diff_day++;
        }
 
        return 0;
    }
 
    // Driver code
     
        var arr = [ 6, 1, 7, 2, 8, 4 ];
        var n = arr.length;
        var b = Array(2).fill(0);
        var tranFee = 2;
 
        max_profit(arr, b, n, tranFee);
 
        document.write(b[0] + ", " + b[1]);
 
 
// This code contributed by Rajput-Ji
 
</script>


Output

8, 1

Complexity Analysis:

  • Time complexity: O(N2)
  • Auxiliary Space: O(1)

Better approach: Same as https://www.geeksforgeeks.org/stock-buy-sell/ but adds diff days as well

Implementation:

C++




// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
pair<int, int> max_profit(int prices[], int n,
                          int transaction_fee = 0)
{
 
  int start = 0;
  int end = 1;
  int profit = 0;
  int max_profit_till_now = INT_MIN;
  int diff = 0;
  while (start < n - 1 && end < n) {
    while (start < n - 1
           && prices[start] > prices[start + 1])
      start += 1;
    end = start + 1;
    while (end < n - 1
           && prices[end] < prices[end + 1]) {
      end += 1;
      if (end == n)
        continue;
    }
    int cur_profit
      = prices[end] - prices[start] - transaction_fee;
    if (cur_profit > 0)
      profit += cur_profit;
    if (max_profit_till_now < cur_profit) {
      max_profit_till_now = cur_profit;
      diff = end - start;
    }
    start = end + 1;
  }
  return make_pair(profit, diff);
}
 
int main()
{
  int prices[] = { 6, 1, 7, 2, 8, 4 };
  int n = 6;
  pair<int, int> res = max_profit(prices, n, 2);
  cout << "(" << res.first << ", " << res.second << ")"
    << endl;
}
 
// This code is contributed by phasing17


Java




// Java program to implement the approach
import java.util.*;
 
class GFG {
  static int[] max_profit(int prices[], int n,
                          int transaction_fee)
  {
 
    int start = 0;
    int end = 1;
    int profit = 0;
    int max_profit_till_now = Integer.MIN_VALUE;
    int diff = 0;
    while (start < n - 1 && end < n) {
      while (start < n - 1
             && prices[start] > prices[start + 1])
        start += 1;
      end = start + 1;
      while (end < n - 1
             && prices[end] < prices[end + 1]) {
        end += 1;
        if (end == n)
          continue;
      }
      int cur_profit = prices[end] - prices[start]
        - transaction_fee;
      if (cur_profit > 0)
        profit += cur_profit;
      if (max_profit_till_now < cur_profit) {
        max_profit_till_now = cur_profit;
        diff = end - start;
      }
      start = end + 1;
    }
    int[] res = { profit, diff };
    return res;
  }
 
  public static void main(String[] args)
  {
    int prices[] = { 6, 1, 7, 2, 8, 4 };
    int n = 6;
    int[] res = max_profit(prices, n, 2);
    System.out.println("(" + res[0] + ", " + res[1]
                       + ")");
  }
}
 
// This code is contributed by phasing17


Python3




from typing import List, Tuple
 
def max_profit(prices: List[int], transaction_fee:int = 0) -> Tuple[int, int]:
    n = len(prices)
    start = 0
    end = 1
    profit = 0
    max_profit_till_now = float('-inf')
    diff = 0
    while start < n - 1 and end < n:
        while start < n - 1 and prices[start] > prices[start + 1]:
            start += 1
        end = start + 1
        while end < n - 1 and prices[end] < prices[end + 1]:
            end += 1
            if end == n:
                continue
        cur_profit = prices[end] - prices[start] - transaction_fee
        if cur_profit > 0:
            profit += cur_profit
        if max_profit_till_now < cur_profit:
            max_profit_till_now = cur_profit
            diff = end - start
        start = end + 1
    return profit, diff
print(max_profit([6, 1, 7, 2, 8, 4], 2))


C#




// C# program to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
  static int[] max_profit(int[] prices, int n,
                          int transaction_fee)
  {
 
    int start = 0;
    int end = 1;
    int profit = 0;
    int max_profit_till_now = Int32.MinValue;
    int diff = 0;
    while (start < n - 1 && end < n) {
      while (start < n - 1
             && prices[start] > prices[start + 1])
        start += 1;
      end = start + 1;
      while (end < n - 1
             && prices[end] < prices[end + 1]) {
        end += 1;
        if (end == n)
          continue;
      }
      int cur_profit = prices[end] - prices[start]
        - transaction_fee;
      if (cur_profit > 0)
        profit += cur_profit;
      if (max_profit_till_now < cur_profit) {
        max_profit_till_now = cur_profit;
        diff = end - start;
      }
      start = end + 1;
    }
    int[] res = { profit, diff };
    return res;
  }
 
  public static void Main(string[] args)
  {
    int[] prices = { 6, 1, 7, 2, 8, 4 };
    int n = 6;
    int[] res = max_profit(prices, n, 2);
    Console.WriteLine("(" + res[0] + ", " + res[1]
                      + ")");
  }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript program to implement the approach
function max_profit(prices, transaction_fee = 0)
{
    let n = prices.length
    let start = 0
    let end = 1
    let profit = 0
    max_profit_till_now = -1000000
    let diff = 0
    while (start < n - 1 && end < n)
    {
        while (start < n - 1 && prices[start] > prices[start + 1])
            start += 1
        end = start + 1
        while (end < n - 1 && prices[end] < prices[end + 1])
        {
            end += 1
            if (end == n)
                continue
        }
        let cur_profit = prices[end] - prices[start] - transaction_fee
        if (cur_profit > 0)
            profit += cur_profit
        if (max_profit_till_now < cur_profit)
        {
            max_profit_till_now = cur_profit
            diff = end - start
        }
        start = end + 1;
    }
    return [profit, diff]
}
 
console.log(max_profit([6, 1, 7, 2, 8, 4], 2))
 
// This code is contributed by phasing17


Output

(8, 1)

Complexity Analysis:

  • Time complexity: O(N)
  • Auxiliary Space: O(1)


Similar Reads

Maximum profit after buying and selling the stocks with transaction fees | Set 2
Given an array arr[] of positive integers representing prices of stocks and an integer transactionFee, the task is to find the maximum profit possible after buying and selling stocks any number of times and giving the transaction fee for each transaction. Examples: Input: arr[] = {6, 1, 7, 2, 8, 4}, transactionFee = 2Output: 8Explanation: A maximum
15 min read
Maximize profit in buying and selling stocks with Rest condition
The price of a stock on each day is given in an array arr[] for N days, the task is to find the maximum profit that can be made by buying and selling the stocks in those days with conditions that the stock must be sold before buying again and stock cannot be bought on the next day of selling a stock. (i.e, rest for at least one day). Examples:  Inp
21 min read
Maximum profit by buying and selling a share at most K times | Greedy Approach
In share trading, a buyer buys shares and sells on a future date. Given the stock price of N days, the trader is allowed to make at most K transactions, where a new transaction can only start after the previous transaction is complete. The task is to find out the maximum profit that a share trader could have made. Examples: Input: prices[] = {10, 2
11 min read
Maximum profit by buying and selling a stock at most twice | Set 2
Given an array prices[] which denotes the prices of the stocks on different days, the task is to find the maximum profit possible after buying and selling the stocks on different days using transaction where at most two transactions are allowed.Note: You cannot engage in multiple transactions at the same time (i.e., you must sell the stock before y
10 min read
Maximum profit by buying and selling a share at most twice
In daily share trading, a buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, the second transaction can only start after the first one is complete (Buy-&gt;sell-&gt;Buy-&gt;sell). Given stock prices throughout the day, find out the maximum profit that a share trader cou
22 min read
Maximum profit by buying and selling a share at most k times
In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made. Examples:Input: Price = [10, 22, 5, 75, 65, 80] K
36 min read
Buy Maximum Stocks if i stocks can be bought on i-th day
In a stock market, there is a product with its infinite stocks. The stock prices are given for N days, where arr[i] denotes the price of the stock on the ith day. There is a rule that a customer can buy at most i stock on the ith day. If the customer has k amount of money initially, find out the maximum number of stocks a customer can buy. For exam
6 min read
Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier
Given an array arr[] consisting of N positive integers, such that arr[i] represents the number of products the ith supplier has and a positive integer, M, the task is to find the maximum profit by selling M products if the profit of a particular product is the same as the number of products left of that supplier. Examples: Input: arr[] = {4, 6}, M
7 min read
Maximum profit using M money and reducing half price of at most K stocks
Given the cost[] and profit[] of N stocks and K tickets, the task is to find the maximum total profit that can be obtained from M initial amount of money using K tickets. Note: A ticket can be used to reduce the cost of any stock to half of the original price and on a particular stock, a ticket can be used only once. Examples: Input: N = 3, cost[]
22 min read
Maximum profit that can be obtained by buying at most K books
Given an integer K and an array arr[] consisting of N integers, where an array element arr[i] represents the price of the ith book. Profit of buying ith book represents max(0, -1 * arr[i]), the task is to find the maximum profit possible by buying at most K books. Examples: Input: arr[] = {-10, 20, -30, 50, -19}, K = 2Output: 49Explanation: Maximum
6 min read