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: 37
💡 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.
Example 3 — Negative Numbers
$ Input: nums = [-1,-2,-3,-4]
Output: 10
💡 Note: Choose indices (2,3) for pair (-3,-4) and (0,1) for pair (-1,-2). Product difference is ((-3)×(-4)) - ((-1)×(-2)) = 12 - 2 = 10.

Constraints

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

Visualization

Tap to expand
Maximum Product Difference INPUT Integer Array nums[] 5 i=0 6 i=1 2 i=2 7 i=3 1 i=4 4 i=5 Goal: Find max product difference (a*b) - (c*d) Input Array: [5, 6, 2, 7, 1, 4] ALGORITHM STEPS 1 Initialize Trackers max1, max2 = MIN_INT min1, min2 = MAX_INT 2 One Pass Scan Track 2 largest values Track 2 smallest values 3 Update Logic If n > max1: shift + update If n < min1: shift + update 4 Calculate Result (max1*max2) - (min1*min2) After One Pass: 7 max1 6 max2 1 min1 2 min2 FINAL RESULT Product Calculation Max Product: 7 x 6 = 42 Min Product: 1 x 2 = 2 Difference: 42 - 2 = 40 (7 x 6) - (1 x 2) OUTPUT 40 OK - Maximum achieved! Key Insight: To maximize (a*b) - (c*d), we need the largest possible product minus the smallest. This means: (largest1 x largest2) - (smallest1 x smallest2). One pass O(n) is optimal! No sorting needed - just track the two largest and two smallest values. TutorialsPoint - Maximum Product Difference Between Two Pairs | One Pass (Optimal) Approach
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