ภารกิจคือการคำนวณกำไรสูงสุดที่สามารถทำได้โดยการขายผลิตภัณฑ์ให้มากที่สุด '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[] ของประเภท int และขนาด 'N' เพื่อจัดเก็บกำไรที่ได้รับจากแต่ละผลิตภัณฑ์
-
สร้างตัวแปร Total of type int เพื่อเก็บผลกำไรสูงสุดขั้นสุดท้าย
-
วนซ้ำจาก i=0 ถึง i
-
ขณะที่อยู่ในลูป ให้ตั้งค่า Profit[i] =Sp[i] – Cp[i]
-
เรียกใช้ฟังก์ชัน sort(Profit, Profit + N, มากกว่า
() ); เพื่อจัดเรียง Profit[] array ใน descendingarray -
วนซ้ำอีกครั้งจาก i=0 ถึง i
-
ขณะที่อยู่ในลูป ให้ตั้งค่าเงื่อนไข if ถ้า(Profit[i]>0) เพื่อตรวจสอบว่าค่าเป็นบวกหรือไม่ และถ้าเป็นเช่นนั้น ให้ตั้งค่า Total+=Profit[i];
-
ผลตอบแทนรวม;
ตัวอย่าง
#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