Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find the Number of Maximum Product Quadruples in C++
Suppose we have one integer array with n elements. We have to find the maximum product of a quadruple in the array. So if the array is like [3, 5, 20, 6, 10], then final product is 6000, and elements in quadruple is 10, 5, 6, 20
To solve this, we will follow these steps −
- Sort the array in ascending order
- Suppose x be the product of last four elements, y be the product of first four elements, and z be the product of first two and second two elements
- Return the max of x, y and z.
Example
#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;
}
Output
Maximum product is 6000
Advertisements
