LeetCode 题解工作台

两个数对之间的最大乘积差

两个数对 (a, b) 和 (c, d) 之间的 乘积差 定义为 (a * b) - (c * d) 。 例如, (5, 6) 和 (2, 7) 之间的乘积差是 (5 * 6) - (2 * 7) = 16 。 给你一个整数数组 nums ,选出四个 不同的 下标 w 、 x 、 y 和 z ,使数…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

class Solution: def maxProductDifference(self, nums: List[int]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

两个数对 (a, b)(c, d) 之间的 乘积差 定义为 (a * b) - (c * d)

  • 例如,(5, 6)(2, 7) 之间的乘积差是 (5 * 6) - (2 * 7) = 16

给你一个整数数组 nums ,选出四个 不同的 下标 wxyz ,使数对 (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 <= 104
  • 1 <= nums[i] <= 104
lightbulb

解题思路

方法一

1
2
3
4
5
class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()
        return nums[-1] * nums[-2] - nums[0] * nums[1]
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

两个数对之间的最大乘积差题解:数组·排序 | LeetCode #1913 简单