LeetCode 题解工作台
两个数对之间的最大乘积差
两个数对 (a, b) 和 (c, d) 之间的 乘积差 定义为 (a * b) - (c * d) 。 例如, (5, 6) 和 (2, 7) 之间的乘积差是 (5 * 6) - (2 * 7) = 16 。 给你一个整数数组 nums ,选出四个 不同的 下标 w 、 x 、 y 和 z ,使数…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
class Solution: def maxProductDifference(self, nums: List[int]) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
两个数对 (a, b) 和 (c, d) 之间的 乘积差 定义为 (a * b) - (c * d) 。
- 例如,
(5, 6)和(2, 7)之间的乘积差是(5 * 6) - (2 * 7) = 16。
给你一个整数数组 nums ,选出四个 不同的 下标 w、x、y 和 z ,使数对 (nums[w], nums[x]) 和 (nums[y], nums[z]) 之间的 乘积差 取到 最大值 。
返回以这种方式取得的乘积差中的 最大值 。
示例 1:
输入:nums = [5,6,2,7,4] 输出:34 解释:可以选出下标为 1 和 3 的元素构成第一个数对 (6, 7) 以及下标 2 和 4 构成第二个数对 (2, 4) 乘积差是 (6 * 7) - (2 * 4) = 34
示例 2:
输入:nums = [4,2,5,9,7,4,8] 输出:64 解释:可以选出下标为 3 和 6 的元素构成第一个数对 (9, 8) 以及下标 1 和 5 构成第二个数对 (2, 4) 乘积差是 (9 * 8) - (2 * 4) = 64
提示:
4 <= nums.length <= 1041 <= nums[i] <= 104
解题思路
方法一
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Consider how to pick elements for maximum product without brute force.
- question_mark
Expect hints about sorting to simplify selecting extreme values.
- question_mark
Watch for questions on handling duplicate numbers or small arrays.
常见陷阱
外企场景- error
Failing to select distinct indices and accidentally using the same element twice.
- error
Not considering that the smallest numbers may also be needed to minimize the second pair product.
- error
Attempting to check all combinations instead of leveraging sorting for efficiency.
进阶变体
外企场景- arrow_right_alt
Maximize the product difference when array elements can be negative.
- arrow_right_alt
Find the maximum product difference for k pairs instead of 2 pairs.
- arrow_right_alt
Compute the maximum sum difference between two pairs instead of product.