LeetCode 题解工作台
有序三元组中的最大值 I
给你一个下标从 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 <= 1001 <= 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
Ability to identify optimized solutions over brute-force ones.
- question_mark
Knowledge of array traversal and manipulation.
- question_mark
Ability to apply nested loops in real-world coding problems.
常见陷阱
外企场景- error
Using brute force without considering optimizations.
- error
Not handling edge cases where no positive triplet exists.
- error
Failing to recognize opportunities to reduce redundant calculations with early termination.
进阶变体
外企场景- arrow_right_alt
Modify the problem to include negative numbers in the array.
- arrow_right_alt
Consider adding constraints where nums contains values within a specific range.
- arrow_right_alt
Adapt the solution for larger arrays while maintaining optimal performance.