Leetcode 1913. Maximum Product Difference Between Two Pairs
You are given an integer array nums
, where the length of nums
is 4 or more. You need to find the maximum product difference between two pairs (a, b)
and (c, d)
where a
and b
are elements from the array nums
as well as c
and d
, and their positions are distinct. The product difference is defined and computed as:
Product Difference = (a * b) - (c * d)
Return the maximum such product difference you can achieve.
nums
will have a length of at least 4 and can be considerably large.nums
?
(a, b)
and (c, d)
include the same elements?
nums
in ascending order.The following Java code implements the sorting approach described:
import java.util.Arrays;
public class MaxProductDifference {
public int maxProductDifference(int[] nums) {
// Step 1: Sort the array
Arrays.sort(nums);
// Step 2: Identify the two largest and two smallest elements
int n = nums.length;
int max1 = nums[n - 1];
int max2 = nums[n - 2];
int min1 = nums[0];
int min2 = nums[1];
// Step 3: Calculate the product differences
int productDifference = (max1 * max2) - (min1 * min2);
return productDifference;
}
public static void main(String[] args) {
MaxProductDifference solution = new MaxProductDifference();
int[] nums = {5, 6, 2, 7, 4};
System.out.println(solution.maxProductDifference(nums)); // Output: 34
}
}
O(n log n)
, where n
is the length of the array.O(1)
.The overall time complexity is dominated by the sorting step, so the time complexity is O(n log n).
In this solution, we efficiently derive the maximum product difference by sorting the array and then using the appropriate elements from the sorted array to perform the calculation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?