LeetCode 题解工作台
有界数组中指定下标处的最大值
给你三个正整数 n 、 index 和 maxSum 。你需要构造一个同时满足下述所有条件的数组 nums (下标 从 0 开始 计数): nums.length == n nums[i] 是 正整数 ,其中 0 abs(nums[i] - nums[i+1]) ,其中 0 nums 中所有元素之和…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
根据题目描述,如果我们确定了 的值为 ,此时我们可以找到一个最小的数组总和。也就是说,在 左侧的数组元素从 一直递减到 ,如果还有剩余的元素,那么剩余的元素都为 ;同理,在 及右侧的数组元素从 一直递减到 ,如果还有剩余的元素,那么剩余的元素都为 。 这样我们就可以计算出数组的总和,如果总和小于等于 ,那么此时的 是合法的。随着 的增大,数组的总和也会增大,因此我们可以使用二分查找的…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你三个正整数 n、index 和 maxSum 。你需要构造一个同时满足下述所有条件的数组 nums(下标 从 0 开始 计数):
nums.length == nnums[i]是 正整数 ,其中0 <= i < nabs(nums[i] - nums[i+1]) <= 1,其中0 <= i < n-1nums中所有元素之和不超过maxSumnums[index]的值被 最大化
返回你所构造的数组中的 nums[index] 。
注意:abs(x) 等于 x 的前提是 x >= 0 ;否则,abs(x) 等于 -x 。
示例 1:
输入:n = 4, index = 2, maxSum = 6 输出:2 解释:数组 [1,1,2,1] 和 [1,2,2,1] 满足所有条件。不存在其他在指定下标处具有更大值的有效数组。
示例 2:
输入:n = 6, index = 1, maxSum = 10 输出:3
提示:
1 <= n <= maxSum <= 1090 <= index < n
解题思路
方法一:二分查找
根据题目描述,如果我们确定了 的值为 ,此时我们可以找到一个最小的数组总和。也就是说,在 左侧的数组元素从 一直递减到 ,如果还有剩余的元素,那么剩余的元素都为 ;同理,在 及右侧的数组元素从 一直递减到 ,如果还有剩余的元素,那么剩余的元素都为 。
这样我们就可以计算出数组的总和,如果总和小于等于 ,那么此时的 是合法的。随着 的增大,数组的总和也会增大,因此我们可以使用二分查找的方法,找到一个最大的且符合条件的 。
为了方便计算数组左侧、右侧的元素之和,我们定义一个函数 ,表示一共有 个元素,且最大值为 的数组的总和。函数 可以分为两种情况:
- 如果 ,那么数组的总和为
- 如果 ,那么数组的总和为
接下来,定义二分的左边界 ,右边界 ,然后二分查找 的值 ,如果 ,那么此时的 是合法的,我们可以将 更新为 ,否则我们将 更新为 。
最后将 作为答案返回即可。
时间复杂度 ,其中 。空间复杂度 。
class Solution:
def maxValue(self, n: int, index: int, maxSum: int) -> int:
def sum(x, cnt):
return (
(x + x - cnt + 1) * cnt // 2 if x >= cnt else (x + 1) * x // 2 + cnt - x
)
left, right = 1, maxSum
while left < right:
mid = (left + right + 1) >> 1
if sum(mid - 1, index) + sum(mid, n - index) <= maxSum:
left = mid
else:
right = mid - 1
return left
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\log (\text{maxSum})) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidate should identify the importance of binary search over the answer space to minimize computation time.
- question_mark
Look for clear understanding of how to calculate array sums given the constraints and how to use greedy methods efficiently.
- question_mark
Ensure the candidate is comfortable explaining the trade-off between maximizing nums[index] and respecting the sum constraint.
常见陷阱
外企场景- error
Failing to handle edge cases, like when nums[index] is at its minimum possible value.
- error
Incorrectly calculating the sum of the array for a given value of nums[index], leading to exceeding the maxSum constraint.
- error
Not considering the effect of the distribution on both sides of the index when constructing the array.
进阶变体
外企场景- arrow_right_alt
What if maxSum is very large compared to n? The binary search will quickly converge to the maximum possible value.
- arrow_right_alt
What if nums[index] is set to the minimum value? This could lead to an unbalanced array and suboptimal performance.
- arrow_right_alt
What if the index is at the edge of the array (either 0 or n-1)? Special care must be taken in constructing the array around the boundary.