Skip to main content

Maximum Product Difference Between Two Pairs - Solution & Explanation

EasyArraySorting14 min read
Practice this problem

Problem Statement

The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

  • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.

Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

Return the maximum such product difference.

 

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 Overview

Problem Overview: You receive an integer array nums. The task is to choose four distinct elements and compute the maximum value of (a * b) - (c * d). To maximize this expression, you want the product of the two largest numbers and subtract the product of the two smallest numbers.

Approach 1: Sort and Pick Extremes (Time: O(n log n), Space: O(1) or O(log n) depending on sort)

Sorting the array makes the structure obvious. After sorting, the two largest values sit at the end of the array and the two smallest values at the beginning. Compute (nums[n-1] * nums[n-2]) - (nums[0] * nums[1]). This works because any other pair would reduce the first product or increase the second one, lowering the final difference. The implementation is short and reliable, which makes it a good baseline solution when using sorting utilities already available in your language.

The algorithm performs a full sort of the array, which costs O(n log n) time. Space usage depends on the sorting implementation but is typically O(1) for in-place sorts or O(log n) due to recursion. If the array is already sorted or you are solving multiple queries on the same sorted data, this approach becomes even more convenient.

Approach 2: Linear Pass with Four Variables (Time: O(n), Space: O(1))

A more optimal solution avoids sorting entirely. Instead, track the two largest and two smallest numbers while scanning the array once. Maintain variables such as max1, max2, min1, and min2. During each iteration, update these values based on comparisons with the current element.

At the end of the scan, compute the result using (max1 * max2) - (min1 * min2). The key insight is that only four numbers influence the final answer: the top two and bottom two values in the array. Everything else is irrelevant. This approach leverages a single pass over the array, making it strictly faster than sorting for large inputs.

This method runs in O(n) time and uses constant O(1) extra space. It’s also straightforward to implement in languages like C++, Java, or Python with simple conditional checks.

Recommended for interviews: The linear pass with four variables is the solution interviewers typically expect. Sorting demonstrates the correct observation about extremes, but the O(n) scan shows stronger algorithmic thinking and better control over array traversal. Mention the sorting approach first if discussing tradeoffs, then implement the linear scan as the optimal answer.

Approach 1: Sort and Pick Extremes

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).

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor β†’

Approach 2: Linear Pass with Four Variables

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.

In this C implementation, we use four variables to retain the largest and smallest elements while iterating through nums, thereby avoiding sorting and achieving linear time complexity.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) since we traverse the array only once.

Space Complexity: O(1) because we use a constant amount of space.

Try this approach in the editor β†’

Approach 3: Default Approach

Code

Python

Java

C++

Go

JavaScript

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Sort and Pick Extremes

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.

Linear Pass with Four Variables

Time Complexity: O(n) since we traverse the array only once.

Space Complexity: O(1) because we use a constant amount of space.

Default Approachβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sort and Pick ExtremesO(n log n)O(1) to O(log n)When simplicity matters or the array is already sorted
Linear Pass with Four VariablesO(n)O(1)Best general solution when you want optimal time without sorting

Video Solution

Maximum Product Difference Between Two - Leetcode 1913 - Python β€’ NeetCodeIO β€’ 6,777 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Maximum Product Difference Between Two Pairs easy or hard?
Maximum Product Difference Between Two Pairs is classified as an Easy problem on LeetCode with a high acceptance rate. The challenge focuses on recognizing that only the two largest and two smallest numbers affect the final result.
Maximum Product Difference Between Two Pairs Python/Java solution
Python and Java implementations typically follow the same logic: either sort the array and compute the result from the extremes, or perform a single pass tracking the two largest and two smallest values. The linear scan solution runs in O(n) time and uses constant memory.
How to solve Maximum Product Difference Between Two Pairs in O(n)?
Scan the array once while maintaining four variables: the two largest numbers and the two smallest numbers seen so far. Update them during each iteration using comparisons. After the loop, compute (max1 * max2) - (min1 * min2) to get the maximum product difference.
What is the best approach for Maximum Product Difference Between Two Pairs?
The optimal approach is a single linear scan that tracks the two largest and two smallest numbers. After one pass, compute (max1 * max2) - (min1 * min2). This method runs in O(n) time and uses O(1) extra space, making it more efficient than sorting.
Is Maximum Product Difference Between Two Pairs asked at Google/Amazon/Meta?
This problem represents a common array scanning pattern often used in coding interviews at companies like Amazon and other product companies. While the exact question may vary, identifying extreme values in a single pass is a frequent interview concept.
What data structure is used in Maximum Product Difference Between Two Pairs?
The problem mainly uses arrays and simple variable tracking. The optimal solution does not require extra data structures; it only maintains four integer variables while iterating through the array.
What is the time complexity of Maximum Product Difference Between Two Pairs?
The optimal solution runs in O(n) time using a single pass to track the two largest and two smallest values. A simpler alternative sorts the array first, which takes O(n log n) time. Both approaches use constant extra space.

Ready to solve this problem?

Practice Maximum Product Difference Between Two Pairs with our built-in code editor and test cases.

Practice on FleetCode