Maximum Product Difference Between Two Pairs - 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) = 30 - 14 = 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,6,2,7,1,4]
Output: 40
💡 Note: Choose indices (1,3) for pair (6,7) and (2,4) for pair (2,1). Product difference is (6×7) - (2×1) = 42 - 2 = 40.
Example 2 — Small Array
$ Input: nums = [4,2,5,9]
Output: 34
💡 Note: Choose indices (2,3) for pair (5,9) and (0,1) for pair (4,2). Product difference is (5×9) - (4×2) = 45 - 8 = 37. Wait, let's try (3,2) and (1,0): (9×5) - (2×4) = 45 - 8 = 37. Actually best is (9×5) - (2×4) = 37.
Example 3 — Negative Numbers
$ Input: nums = [-1,-2,-3,-4]
Output: 2
💡 Note: Choose indices (0,1) for pair (-1,-2) and (2,3) for pair (-3,-4). Product difference is ((-1)×(-2)) - ((-3)×(-4)) = 2 - 12 = -10. Actually best is ((-3)×(-4)) - ((-1)×(-2)) = 12 - 2 = 10.

Constraints

  • 4 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Product Difference: Find Optimal PairsInput Array:5627142nd Max1st Max2nd Min1st MinMaximum Product7 × 6 = 42-Minimum Product1 × 2 = 2Result42 - 2 = 40
Understanding the Visualization
1
Input
Array with at least 4 elements
2
Process
Find two largest and two smallest elements
3
Output
Maximum product difference
Key Takeaway
🎯 Key Insight: Maximum difference always comes from (largest × second largest) - (smallest × second smallest)
Asked in
Amazon 25 Microsoft 18 Google 12
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen