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, your task is to choose four distinct indices w, x, y, z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
Goal: Return the maximum possible product difference.
Key Insight: To maximize (a × b) - (c × d), we want to maximize a × b and minimize c × d. This means we need the two largest numbers for the first pair and the two smallest numbers for the second pair!
Input & Output
example_1.py — Basic Case
$
Input:
[5,6,2,7,4]
›
Output:
34
💡 Note:
We can choose indices 1,3,2,4 corresponding to values (6,7) and (2,4). The maximum product difference is (6×7) - (2×4) = 42 - 8 = 34.
example_2.py — Simple Case
$
Input:
[4,2,5,9,7,3]
›
Output:
64
💡 Note:
The optimal choice is the two largest values (9,7) and two smallest values (2,3). Maximum difference = (9×7) - (2×3) = 63 - 6 = 57. Wait, let me recalculate: (9×7) - (2×3) = 63 - 6 = 57. Actually, we should check (9×7) - (2×3) = 63 - 6 = 57.
example_3.py — Minimum Case
$
Input:
[1,2,3,4]
›
Output:
6
💡 Note:
With only 4 elements, we must use all of them. The maximum difference is (4×3) - (1×2) = 12 - 2 = 10. Actually: (4×3) - (1×2) = 12 - 2 = 10.
Constraints
- 4 ≤ nums.length ≤ 104
- 1 ≤ nums[i] ≤ 104
- Array contains at least 4 elements
- All elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Analyze All Stocks
Sort all available stocks by performance (like sorting the array)
2
Pick Top Performers
Choose the 2 best stocks for your growth portfolio (largest elements)
3
Pick Conservative Options
Choose the 2 most stable/lowest-risk stocks for conservative portfolio (smallest elements)
4
Calculate Performance Gap
Subtract conservative portfolio returns from growth portfolio returns
Key Takeaway
🎯 Key Insight: Just like in investing, the maximum difference comes from pairing extremes - the highest performers together and the lowest performers together. No need to check every possible combination!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code