กำหนดให้งานคือการคำนวณจำนวนคู่สูงสุด arr[i] + arr[j] ที่หารด้วย K โดยที่ arr[] คืออาร์เรย์ที่มีจำนวนเต็ม N
ด้วยเงื่อนไขว่าหมายเลขดัชนีเฉพาะไม่สามารถใช้มากกว่าหนึ่งคู่ได้
ป้อนข้อมูล
arr[]={1, 2 ,5 ,8 ,3 }, K=2 ผลผลิต
2
คำอธิบาย − คู่ที่ต้องการคือ:(0,2), (1,3) เป็น 1+5=6 และ 2+8=10 ทั้ง 6 และ 10 หารด้วย 2 ลงตัว
คำตอบอื่นอาจเป็นคู่:(0,4), (1,3) หรือ (2,4), (1,3) แต่คำตอบยังคงเหมือนเดิม นั่นคือ 2
ป้อนข้อมูล
arr[]={1 ,3 ,5 ,2 ,3 ,4 }, K=3 ผลผลิต
3
แนวทางที่ใช้ในโปรแกรมด้านล่างดังนี้
-
ในตัวแปร n ชนิด int เก็บขนาดของอาร์เรย์
-
ในฟังก์ชัน MaxPairs() ใช้แผนที่แบบไม่เรียงลำดับและเพิ่มค่าเป็น um[arr[i]%K] ทีละรายการสำหรับแต่ละองค์ประกอบของอาร์เรย์
-
ทำซ้ำและรับทุกค่า um ที่เป็นไปได้
-
หากค่า um เป็นศูนย์ จำนวนคู่จะกลายเป็น um[0]/2
-
จากนั้นสามารถสร้างคู่จากทุกค่า um 'a' โดยใช้ค่าต่ำสุดของ (um[a], um[Ka])
-
ลบออกจากค่า um จำนวนคู่ที่ใช้
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int MaxPairs(int arr[], int size, int K){
unordered_map<int, int> um;
for (int i = 0; i < size; i++){
um[arr[i] % K]++;
}
int count = 0;
/*Iteration for all the number that are less than the hash value*/
for (auto it : um){
// If the number is 0
if (it.first == 0){
//Taking half since same number
count += it.second / 2;
if (it.first % 2 == 0){
um[it.first] = 0;
}
else{
um[it.first] = 1;
}
}
else{
int first = it.first;
int second = K - it.first;
// Check for minimal occurrence
if (um[first] < um[second]){
//Taking the minimal
count += um[first];
//Subtracting the used pairs
um[second] -= um[first];
um[first] = 0;
}
else if (um[first] > um[second]){
// Taking the minimal
count += um[second];
//Subtracting the used pairs
um[first] -= um[second];
um[second] = 0;
}
else{
//Checking if the numbers are same
if (first == second){
//If same then number of pairs will be half
count += it.second / 2;
//Checking for remaining
if (it.first % 2 == 0)
um[it.first] = 0;
else
um[it.first] = 1;
}
else{
//Storing the number of pairs
count += um[first];
um[first] = 0;
um[second] = 0;
}
}
}
}
return count;
}
//Main function
int main(){
int arr[] = { 3, 6, 7, 9, 4, 4, 10 };
int size = sizeof(arr) / sizeof(arr[0]);
int K = 2;
cout<<"Maximize the number of sum pairs which are divisible by K is: "<<MaxPairs(arr, size, K);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น เราจะได้ผลลัพธ์ต่อไปนี้ -
Maximize the number of sum pairs which are divisible by K is: 3