Maximize the profit by selling at-most M products in C++

Given the task is to calculate the maximum profit that can be made by selling at-most ‘M’ products.

The total number of products are ‘N’ and the cost price and the selling price of each product is given in the lists CP[] and SP[] respectively.


N=6, M=4



Explanation − The profit obtained from selling all the products are 0,6,5,8,3,9 respectively.

So, in order to make maximum profit by selling only 4 products, the products with the highest profit need to be chosen, that is, product number 2,3,4 and 6.

Maximum profit= 6+5+8+9= 28


N=3, M=2



Approach used in the below program as follows

  • Create an array Profit[] of type int and size ‘N’ to store the profit obtained from each product.

  • Create a variable Total of type int to store the final maximum profit.

  • Loop from i=0 till i<N

  • While in loop, set Profit[i] = Sp[i] – Cp[i]

  • Call function sort(Profit, Profit + N, greater<int>() ); to arrange the Profit[] array in descending array.

  • Again loop from i=0 till i<M

  • While in loop set an if condition, if(Profit[i]>0) to check if the value positive or not and if so then set total+=Profit[i];

  • return total;


#include <bits/stdc++.h>
using namespace std;
//Function to find profit
int MaxProfit(int N, int M, int Cp[], int Sp[]){
   int Profit[N];
   int total = 0;
   //Calculating profit from each product
   for (int i = 0; i < N; i++)
      Profit[i] = Sp[i] - Cp[i];
   //Arranging profit array in descending order
   sort(Profit, Profit + N, greater<int>());
   //Adding the best M number of profits
   for (int i = 0; i < M; i++){
      if (Profit[i] > 0)
         total += Profit[i];
   return total;
//Main function
int main(){
   int MP;
   int N=6,M=4;
   int CP[] = { 1, 9, 5, 8, 2, 11 };
   int SP[] = { 1, 15, 10, 16, 5, 20 };
   MP = MaxProfit(N, M, CP, SP);
   cout<<”Maximum Profit:”<<MP;
   return 0;


If we run the above code we will get the following output −

Maximum Profit: 28