0%

[筆記] Leetcode - 1913. Maximum Product Difference Between Two Pairs

https://leetcode.com/problems/maximum-product-difference-between-two-pairs/

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

Example 1:

1
2
3
4
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).
The product difference is (6 * 7) - (2 * 4) = 34.

Example 2:

1
2
3
4
Input: nums = [4,2,5,9,7,4,8]
Output: 64
Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
min_num1, min_num2 = math.inf, math.inf
max_num1, max_num2 = -math.inf, -math.inf

for number in nums:
if number > max_num1:
max_num1, max_num2 = number, max_num1
elif number > max_num2:
max_num2 = number

if number < min_num1:
min_num1, min_num2 = number, min_num1
elif number < min_num2:
min_num2 = number

return max_num1 * max_num2 - min_num1 * min_num2