LeetCode 题解工作台
最小化数组中的最大值
给你一个下标从 0 开始的数组 nums ,它含有 n 个非负整数。 每一步操作中,你需要: 选择一个满足 1 的整数 i ,且 nums[i] > 0 。 将 nums[i] 减 1 。 将 nums[i - 1] 加 1 。 你可以对数组执行 任意 次上述操作,请你返回可以得到的 nums 数组…
5
题型
4
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
最小化数组的最大值,容易想到二分查找。我们二分枚举数组的最大值 ,找到一个满足题目要求的、且值最小的 即可。 时间复杂度 $O(n \times \log M)$,其中 为数组的长度,而 为数组中的最大值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的数组 nums ,它含有 n 个非负整数。
每一步操作中,你需要:
- 选择一个满足
1 <= i < n的整数i,且nums[i] > 0。 - 将
nums[i]减 1 。 - 将
nums[i - 1]加 1 。
你可以对数组执行 任意 次上述操作,请你返回可以得到的 nums 数组中 最大值 最小 为多少。
示例 1:
输入:nums = [3,7,1,6] 输出:5 解释: 一串最优操作是: 1. 选择 i = 1 ,nums 变为 [4,6,1,6] 。 2. 选择 i = 3 ,nums 变为 [4,6,2,5] 。 3. 选择 i = 1 ,nums 变为 [5,5,2,5] 。 nums 中最大值为 5 。无法得到比 5 更小的最大值。 所以我们返回 5 。
示例 2:
输入:nums = [10,1] 输出:10 解释: 最优解是不改动 nums ,10 是最大值,所以返回 10 。
提示:
n == nums.length2 <= n <= 1050 <= nums[i] <= 109
解题思路
方法一:二分查找
最小化数组的最大值,容易想到二分查找。我们二分枚举数组的最大值 ,找到一个满足题目要求的、且值最小的 即可。
时间复杂度 ,其中 为数组的长度,而 为数组中的最大值。
class Solution:
def minimizeArrayValue(self, nums: List[int]) -> int:
def check(mx):
d = 0
for x in nums[:0:-1]:
d = max(0, d + x - mx)
return nums[0] + d <= mx
left, right = 0, max(nums)
while left < right:
mid = (left + right) >> 1
if check(mid):
right = mid
else:
left = mid + 1
return left
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate is familiar with binary search applications in optimization problems.
- question_mark
The candidate demonstrates understanding of greedy algorithms in combination with binary search.
- question_mark
The candidate efficiently manages the prefix sum to validate the feasibility of each operation.
常见陷阱
外企场景- error
Misunderstanding the operation limits may lead to incorrect binary search bounds.
- error
Failing to efficiently validate each candidate maximum value within the binary search process.
- error
Not using prefix sums or an alternative efficient method for checking feasibility in large arrays.
进阶变体
外企场景- arrow_right_alt
In some variants, the number of allowed operations may be restricted, requiring additional constraints handling.
- arrow_right_alt
The problem may be extended to multi-dimensional arrays, increasing the complexity of both binary search and validation.
- arrow_right_alt
Instead of greedy operations, some variants may involve dynamic programming or different optimization methods for determining the result.