Maximum Product Difference Between Two Pairs — LeetCode 1913 Python Solution

EasyArraySorting
Problem
#1913
Pattern
Sorting
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()
        return nums[-1] * nums[-2] - nums[0] * nums[1]

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1913. Maximum Product Difference Between Two Pairs is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1913. Maximum Product Difference Between Two Pairs?
LeetCode 1913. Maximum Product Difference Between Two Pairs is rated Easy on LeetCode.
What topics does LeetCode 1913. Maximum Product Difference Between Two Pairs cover?
LeetCode 1913. Maximum Product Difference Between Two Pairs is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview