
Problem Statement
The concept of "product difference" is defined for two pairs of numbers (a, b)
and (c, d)
as (a * b) - (c * d)
. Given an integer array nums
, the goal is to find four distinct indices such that the product difference between the two pairs formed by these indices is maximized. In simpler terms, you need to select indices w
, x
, y
, and z
from the array such that the difference between the product of nums[w]
and nums[x]
, and that of nums[y]
and nums[z]
is the largest possible. The function should return this maximum product difference.
Examples
Example 1
Input:
nums = [5,6,2,7,4]
Output:
34
Explanation:
We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 * 7) - (2 * 4) = 34.
Example 2
Input:
nums = [4,2,5,9,7,4,8]
Output:
64
Explanation:
We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 * 8) - (2 * 4) = 64.
Constraints
4 <= nums.length <= 104
1 <= nums[i] <= 104
Approach and Intuition
To maximize the product difference
(a * b) - (c * d)
, aim for(a * b)
to be as large as possible and(c * d)
to be as small as possible. This observation is foundational for our strategy.Extract the two largest and the two smallest elements from
nums
. This is because the product of the two largest numbers will yield the highest possible product from the array, and similarly, the product of the two smallest numbers will tend to be the smallest (or most negative if negatives were possible, but constraints forbid negatives).How do we efficiently find these numbers?
- Sort the array: Once
nums
is sorted, the two largest elements will be the last two elements of the sorted array, and the two smallest will be the first two elements. - Calculate based on the sorted positions: If we denote sorted
nums
asnums_sorted
, then:- The two largest numbers can be accessed as
nums_sorted[-1]
andnums_sorted[-2]
. - The two smallest numbers can be accessed as
nums_sorted[0]
andnums_sorted[1]
.
- The two largest numbers can be accessed as
- Compute the product difference: Using the four identified numbers, compute
(nums_sorted[-1] * nums_sorted[-2]) - (nums_sorted[0] * nums_sorted[1])
.
- Sort the array: Once
Given the constraints (
4 <= nums.length <= 104
and1 <= nums[i] <= 104
), this method is efficient. Sorting the array will takeO(n log n)
, which is reasonable for the input size limit. This approach ensures that we automatically respect the condition of choosing four distinct indices since the largest and smallest pairs are distinct by definition in sorted order.
By focusing on maximizing the primary product and minimizing the secondary product via sorting and strategic selection, we can robustly determine the maximum product difference achievable.
Solutions
- C++
- Java
- Python
class Solution {
public:
int maximumProductDifference(vector<int>& nums) {
int largest = 0;
int secondLargest = 0;
int tiniest = INT_MAX;
int secondTiniest = INT_MAX;
for (int value : nums) {
if (value > largest) {
secondLargest = largest;
largest = value;
} else {
secondLargest = max(secondLargest, value);
}
if (value < tiniest) {
secondTiniest = tiniest;
tiniest = value;
} else {
secondTiniest = min(secondTiniest, value);
}
}
return largest * secondLargest - tiniest * secondTiniest;
}
};
The provided C++ code defines a solution for calculating the maximum product difference between two pairs within an integer array. The function maximumProductDifference
calculates this by first identifying the two largest and two smallest elements in the array.
Here's a breakdown of how the code achieves this:
- Initializes four integer variables:
largest
,secondLargest
set to 0, andtiniest
,secondTiniest
set toINT_MAX
to hold the largest and smallest values respectively. - Iterates through each integer in the
nums
array using a for loop. For each element:- Updates
largest
andsecondLargest
if the current value is greater thanlargest
. If not, updatessecondLargest
if it's greater than the current value ofsecondLargest
. - Updates
tiniest
andsecondTiniest
if the current value is less thantiniest
. If not, updatessecondTiniest
if it is greater than the current value ofsecondTiniest
.
- Updates
- Finally, it calculates the product difference by multiplying
largest
withsecondLargest
and subtracting the product oftiniest
andsecondTiniest
from it.
This algorithm effectively and efficiently finds the required elements to determine the maximum product difference without sorting the array, thus operating in linear time complexity O(n). This method ensures optimal performance even for large input arrays.
class Solution {
public int maxProductDifference(int[] values) {
int max1 = 0;
int max2 = 0;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for (int value : values) {
if (value > max1) {
max2 = max1;
max1 = value;
} else {
max2 = Math.max(max2, value);
}
if (value < min1) {
min2 = min1;
min1 = value;
} else {
min2 = Math.min(min2, value);
}
}
return max1 * max2 - min1 * min2;
}
}
The provided Java code solves the problem of finding the maximum product difference between two pairs of elements in an array. The approach involves calculating the maximum product of two values and the minimum product of two other values from the given array, then computing the difference of these two products.
- Start by initializing two sets of variables to keep track of the highest values (
max1
,max2
) and the lowest values (min1
,min2
). - Iterate through each element in the array:
- Update
max1
andmax2
to always contain the largest and second-largest values in the array. - Similarly, keep
min1
andmin2
updated to hold the smallest and second-smallest values.
- Update
- After exiting the loop, calculate the products
max1 * max2
andmin1 * min2
. - The function returns the result by subtracting the product of the smallest pair from the product of the largest pair, yielding the maximum product difference.
This method ensures that one captures all necessary comparisons in one traversal of the array, achieving an optimal solution in terms of time and space efficiency.
class Solution:
def computeMaxProductDifference(self, values: List[int]) -> int:
max1 = 0
max2 = 0
min1 = float('inf')
min2 = float('inf')
for value in values:
if value > max1:
max2 = max1
max1 = value
elif value > max2:
max2 = value
if value < min1:
min2 = min1
min1 = value
elif value < min2:
min2 = value
return max1 * max2 - min1 * min2
This Python solution is designed to find the maximum product difference between two pairs of numbers from a given list. The main concept is to identify the two highest and two lowest values from the list in a single iteration. This process ensures efficiency, saving time by avoiding multiple full scans of the array.
The strategy can be summarized as follows:
- Initialize four variables — two to store the maximum values (
max1
,max2
) and two to store the minimum values (min1
,min2
). Setmax1
andmax2
to zero andmin1
andmin2
to infinity (float('inf')
), which acts as a placeholder until the actual list values are checked. - Iterate over each value in the list
values
:- Update
max1
andmax2
if you find a value greater thanmax1
ormax2
. - Similarly, update
min1
andmin2
if a value less thanmin1
ormin2
is found.
- Update
After identifying these four critical values, compute the desired result by calculating the expression max1 * max2 - min1 * min2
.
This method is not only direct but also optimal with an O(n) complexity, as it runs through the list a single time, performing constant time checks and updates during each iteration. This ensures that the program is suitable for large datasets.
No comments yet.