พิจารณาว่าเรามีอาร์เรย์ A มีองค์ประกอบที่แตกต่างกัน n รายการ เราต้องหาคู่ (x, y) จากอาร์เรย์ A เพื่อให้ผลคูณของ x และ y มีค่าสูงสุด อาร์เรย์อาจมีองค์ประกอบบวกหรือลบ สมมติว่าอาร์เรย์มีลักษณะดังนี้:A =[-1, -4, -3, 0, 2, -5] คู่จะเป็น (-4, -5) เนื่องจากผลคูณมีค่าสูงสุด
เพื่อแก้ปัญหานี้ เราต้องติดตามตัวเลขสี่ตัว ได้แก่ positive_max, positive_second_max, negative_max, negative_second_max ในตอนท้ายหาก (positive_max * positive_second_max) มากกว่า (negative_max * negative_second_max) ให้คืนค่าคู่ค่าบวก มิฉะนั้น ให้คืนค่าคู่ค่าลบ
ตัวอย่าง
#include<iostream>
#include<cmath>
using namespace std;
void maxProdPair(int arr[], int n) {
if (n < 2) {
cout << "No pair is present";
return;
}
if (n == 2) {
cout << "(" << arr[0] << ", " << arr[1] << ")" << endl;
return;
}
int pos_max = INT_MIN, pos_second_max = INT_MIN;
int neg_max = INT_MIN, neg_second_max = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > pos_max) {
pos_second_max = pos_max;
pos_max = arr[i];
} else if (arr[i] > pos_second_max)
pos_second_max = arr[i];
if (arr[i] < 0 && abs(arr[i]) > abs(neg_max)) {
neg_second_max = neg_max;
neg_max = arr[i];
}
else if(arr[i] < 0 && abs(arr[i]) > abs(neg_second_max))
neg_second_max = arr[i];
}
if (neg_max*neg_second_max > pos_max*pos_second_max)
cout << "(" << neg_max << ", " << neg_second_max << ")" << endl;
else
cout << "(" << pos_max << ", " << pos_second_max << ")" << endl;
}
int main() {
int arr[] = {-1, -4, -3, 0, 2, -5};
int n = sizeof(arr)/sizeof(arr[0]);
maxProdPair(arr, n);
} ผลลัพธ์
(-5, -4)