Minimize Maximum of Array Problem
#2439
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2439.
You are given a 0-indexed array nums comprising of n non-negative integers.
In one operation, you must:
- Choose an integer
isuch that1 <= i < nandnums[i] > 0. - Decrease
nums[i]by 1. - Increase
nums[i - 1]by 1.
Return the minimum possible value of the maximum integer of nums after performing any number of operations.
Example 1:
Input: nums = [3,7,1,6]
Output: 5
Explanation:
One set of optimal operations is as follows:
1. Choose i = 1, and nums becomes [4,6,1,6].
2. Choose i = 3, and nums becomes [4,6,2,5].
3. Choose i = 1, and nums becomes [5,5,2,5].
The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.
Therefore, we return 5.
Example 2:
Input: nums = [10,1]
Output: 10
Explanation:
It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.
Constraints:
n == nums.length2 <= n <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Binary Search
If the maximum can be brought down to mx, it can also be brought down to any larger value, so binary search the smallest feasible mx.
To check mx, sweep from the right and carry the excess: for each i > 0, d = max(0, d + nums[i] - mx) is what must be pushed to the left. It works when nums[0] + d <= mx.
Complexity: The time complexity is O(n log M), where n is the length of the array and M its maximum.
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