LeetCode 题解工作台
有序三元组中的最大值 II
给你一个下标从 0 开始的整数数组 nums 。 请你从所有满足 i 的下标三元组 (i, j, k) 中,找出并返回下标三元组的最大值。如果所有满足条件的三元组的值都是负数,则返回 0 。 下标三元组 (i, j, k) 的值等于 (nums[i] - nums[j]) * nums[k] 。 示…
1
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·driven
答案摘要
我们用两个变量 和 分别维护前缀最大值和最大差值,用一个变量 维护答案。初始时,这些变量都为 。 接下来,我们枚举数组的每个元素 作为 ,首先更新答案 $\textit{ans} = \max(\textit{ans}, \textit{mxDiff} \times x)$,然后我们更新最大差值 $\textit{mxDiff} = \max(\textit{mxDiff}, \texti…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。
请你从所有满足 i < j < k 的下标三元组 (i, j, k) 中,找出并返回下标三元组的最大值。如果所有满足条件的三元组的值都是负数,则返回 0 。
下标三元组 (i, j, k) 的值等于 (nums[i] - nums[j]) * nums[k] 。
示例 1:
输入:nums = [12,6,1,2,7] 输出:77 解释:下标三元组 (0, 2, 4) 的值是 (nums[0] - nums[2]) * nums[4] = 77 。 可以证明不存在值大于 77 的有序下标三元组。
示例 2:
输入:nums = [1,10,3,4,19] 输出:133 解释:下标三元组 (1, 2, 4) 的值是 (nums[1] - nums[2]) * nums[4] = 133 。 可以证明不存在值大于 133 的有序下标三元组。
示例 3:
输入:nums = [1,2,3] 输出:0 解释:唯一的下标三元组 (0, 1, 2) 的值是一个负数,(nums[0] - nums[1]) * nums[2] = -3 。因此,答案是 0 。
提示:
3 <= nums.length <= 1051 <= nums[i] <= 106
解题思路
方法一:维护前缀最大值和最大差值
我们用两个变量 和 分别维护前缀最大值和最大差值,用一个变量 维护答案。初始时,这些变量都为 。
接下来,我们枚举数组的每个元素 作为 ,首先更新答案 ,然后我们更新最大差值 ,最后更新前缀最大值 。
枚举完所有元素后,返回答案 。
时间复杂度 ,其中 是数组长度。空间复杂度 。
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
ans = mx = mx_diff = 0
for x in nums:
ans = max(ans, mx_diff * x)
mx_diff = max(mx_diff, mx - x)
mx = max(mx, x)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
They want you to notice that j is the fixed middle and the formula can be split into best left and best right choices.
- question_mark
They expect you to reject O(n^3) triplet enumeration and move to prefix and suffix preprocessing.
- question_mark
They may watch whether you remember the answer is 0 when the best computed product is still negative.
常见陷阱
外企场景- error
Using the global maximum on the left or right without enforcing i < j < k, which breaks the ordered triplet condition.
- error
Forgetting to clamp the final result to 0, which gives the wrong answer on arrays like [1,2,3].
- error
Computing the product in a type that is too small, since values can exceed 32-bit integer range during multiplication.
进阶变体
外企场景- arrow_right_alt
Replace the right-side maximum with a suffix minimum if the formula changes and the multiplier can benefit from smaller values.
- arrow_right_alt
Ask for the indices of the optimal triplet instead of only the value, which means storing where each prefix and suffix maximum came from.
- arrow_right_alt
Convert the same ordered-triplet idea into a streaming version where you maintain the best left value and best left-minus-middle score as you scan.