在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP