Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Maximum Sum of Products of Two Arrays in C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมหาผลรวมสูงสุดของผลคูณของสองอาร์เรย์

เราจะได้รับสองอาร์เรย์ขนาดเท่ากัน งานคือหาผลรวมสูงสุดโดยการคูณองค์ประกอบหนึ่งจากอาร์เรย์แรกกับหนึ่งจากอาร์เรย์ที่สอง (จับคู่กันทีละคู่)

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

int maximumSOP(int *a, int *b, int n) {
    int sop = 0;
    sort(a, a + n);
    sort(b, b + n);
    for (int i = 0; i < n; i++)
        sop += a[i] * b[i];
    return sop;
}

int main() {
    int A[] = {1, 2, 3};
    int B[] = {4, 5, 1};
    int n = sizeof(A) / sizeof(A[0]);
    cout << maximumSOP(A, B, n);
    return 0;
}

เอาต์พุต

24