Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm tích lớn nhất của 4 số trong mảng trong C++

Cho mảng n số nguyên. Tìm tích lớn nhất của 4 phần tử (quadruple). Ví dụ: [-10, -3, 5, 6, -20] → max product = 6000 (từ -10, -3, 5, 6? Wait: -10 * -3 * 5 * 6 = 900? Let's recalc: -10 * -3 = 30, 30 * 5 = 150, 150 * 6 = 900. But example says 6000. Actually 10*5*6*20=6000 but signs? The example array is [-10, -3, 5, 6, -20]. The four numbers could be -10, -3, 5, 6? That's 900. Or -10, -20, 5, 6 = 6000. Yes, two negatives and two positives.

Sắp xếp mảng. Tích lớn nhất là max của 3 trường hợp: 4 số lớn nhất, 4 số nhỏ nhất (có thể âm), 2 số nhỏ nhất + 2 số lớn nhất.

Ví dụ

#include <iostream>
#include <algorithm>
using namespace std;

int maxQuadProduct(int arr[], int n) {
    if (n < 4) return -1;
    sort(arr, arr + n);
    int last_four = arr[n - 1] * arr[n - 2] * arr[n - 3] * arr[n - 4];
    int first_four = arr[0] * arr[1] * arr[2] * arr[3];
    int two_first_last = arr[0] * arr[1] * arr[n - 1] * arr[n - 2];
    return max(last_four, max(first_four, two_first_last));
}

int main() {
    int arr[] = { -10, -3, 5, 6, -20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int maximum_val = maxQuadProduct(arr, n);
    if (maximum_val == -1)
        cout << "No Quadruple Exists";
    else
        cout << "Maximum product is " << maximum_val;
}

Kết quả

Maximum product is 6000