LeetCode 题解工作台
数组中两元素的最大乘积
给你一个整数数组 nums ,请你选择数组的两个不同下标 i 和 j , 使 (nums[i]-1)*(nums[j]-1) 取得最大值。 请你计算并返回该式的最大值。 示例 1: 输入: nums = [3,4,5,2] 输出: 12 解释: 如果选择下标 i=1 和 j=2(下标从 0 开始),…
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
双重循环,枚举所有的下标对,求出 $(nums[i]-1) \times (nums[j]-1)$ 的最大值。其中 $i \neq j$。 时间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。
请你计算并返回该式的最大值。
示例 1:
输入:nums = [3,4,5,2] 输出:12 解释:如果选择下标 i=1 和 j=2(下标从 0 开始),则可以获得最大值,(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12 。
示例 2:
输入:nums = [1,5,4,5] 输出:16 解释:选择下标 i=1 和 j=3(下标从 0 开始),则可以获得最大值 (5-1)*(5-1) = 16 。
示例 3:
输入:nums = [3,7] 输出:12
提示:
2 <= nums.length <= 5001 <= nums[i] <= 10^3
解题思路
方法一:暴力枚举
双重循环,枚举所有的下标对,求出 的最大值。其中 。
时间复杂度 。
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = 0
for i, a in enumerate(nums):
for b in nums[i + 1 :]:
ans = max(ans, (a - 1) * (b - 1))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for top elements quickly instead of testing every pair.
- question_mark
Expect discussion of both sorting and linear scan methods.
- question_mark
Clarify array constraints to justify linear-time optimization.
常见陷阱
外企场景- error
Forgetting to subtract 1 from each number before multiplying.
- error
Assuming elements can repeat without checking distinct indices.
- error
Using nested loops unnecessarily when a linear scan suffices.
进阶变体
外企场景- arrow_right_alt
Find the maximum product of k elements in an array.
- arrow_right_alt
Compute the maximum product modulo a large prime.
- arrow_right_alt
Find the pair with the maximum product where elements must be consecutive.