在C++中,通过最多销售M件产品来最大化利润


给定的任务是计算通过最多销售‘M’件产品所能获得的最大利润。

产品的总数为‘N’,每件产品的成本价和售价分别在列表CP[]和SP[]中给出。

输入 

N=6, M=4
CP[]={1,9,5,8,2,11}
SP[]={1,15,10,16,5,20}

输出 

28

说明 − 销售所有产品的利润分别为0,6,5,8,3,9。

因此,为了通过只销售4件产品获得最大利润,需要选择利润最高的那些产品,即产品编号2,3,4和6。

最大利润 = 6+5+8+9 = 28

输入 

N=3, M=2
CP[]={10,20,30}
SP[]={19,22,38}

输出 

17

下面程序中使用的方案如下

  • 创建一个名为Profit[]的整型数组,大小为‘N’,用于存储每件产品获得的利润。

  • 创建一个名为Total的整型变量,用于存储最终的最大利润。

  • 循环从i=0到i<N

  • 在循环中,设置Profit[i] = Sp[i] – Cp[i]

  • 调用函数sort(Profit, Profit + N, greater<int>() ); 将Profit[]数组按降序排列。

  • 再次循环从i=0到i<M

  • 在循环中设置一个if条件,if(Profit[i]>0) 检查该值是否为正数,如果是,则设置total+=Profit[i];

  • 返回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];
      else
         break;
   }
   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;
}

输出

如果我们运行上述代码,我们将得到以下输出:

Maximum Profit: 28

更新于:2020年8月14日

400 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.