Sponsored
Sponsored
This approach involves sorting the array and then selecting the appropriate numbers to form two pairs. The largest two numbers should form one pair to maximize the product, and the smallest two numbers should form the other pair to minimize the product. This ensures that the product difference is as large as possible:
1. Sort the array nums
.
2. Select the two largest numbers for (a, b)
and the two smallest numbers for (c, d)
.
3. Compute the product difference as (a * b) - (c * d)
.
Time Complexity: O(n log n) due to sorting the array, where n
is the length of the array.
Space Complexity: O(1) as we sort the array in place and use a constant amount of extra space.
1#include <stdio.h>
2#include <stdlib.h>
3
4int cmpfunc(const void *a, const void *b) {
The given C solution sorts the array using qsort()
and calculates the maximum product difference by multiplying the two largest and two smallest numbers. It prints the result after computing.
Instead of sorting, we can solve the problem in linear time by keeping track of the four numbers we need: the two largest numbers and the two smallest numbers:
1. Initialize variables to hold the minimum two and maximum two values seen so far.
2. Iterate through the array, updating these variables accordingly.
3. Calculate the product difference with the two largest and two smallest values obtained.
Time Complexity: O(n) since we traverse the array only once.
Space Complexity: O(1) because we use a constant amount of space.
In Java, the solution efficiently keeps track of maximum and minimum pairs by iterating once through the array, enhancing the solution's performance by bypassing sorting.