Maximum Product Difference Between Two Pairs

The product difference between two pairs (a, b) and (c, d) is (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y and z so that the product difference between (nums[w], nums[x]) and (nums[y], nums[z]) is as large as possible, and return that maximum.

30:00

Maximum Product Difference Between Two Pairs
easy
Free written solution
Topics
Companies

The product difference between two pairs (a, b) and (c, d) is (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y and z so that the product difference between (nums[w], nums[x]) and (nums[y], nums[z]) is as large as possible, and return that maximum.

Example 1:
Input: {"nums":[5,6,2,7,4]}
Output: 34
Constraints:
  • 4≤nums.length≤1044 \leq \text{nums.length} \leq 10^4

  • 1≤nums[i]≤1041 \leq \text{nums}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[5,6,2,7,4]}

The best difference uses the two largest numbers for the first product and the two smallest for the second. Track both pairs in one pass.

nums

5
6
2
7
4

two largest

big1

-

big2

-

not filled yet

two smallest

small1

∞

small2

∞

not filled yet

Variables
VariableValue
big10
big20
small1inf
small2inf
DepthFunction Call
Stack empty
0/8