Minimize Maximum of Array — LeetCode 2439 Python Solution

MediumGreedyArrayBinary SearchDynamic ProgrammingPrefix Sum
Problem
#2439
Pattern
Prefix Sum
Reading time
3 min

The problem

You are given a 0-indexed array nums comprising of n non-negative integers. In one operation, you must: Choose an integer i such that 1 <= i < n and nums[i] > 0.

Example

Input
nums = [3,7,1,6]
Output
5
Explanation
One set of optimal operations is as follows:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log M), where n is the length of the array, and M is the maximum value in the array
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2439. Minimize Maximum of Array is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2439. Minimize Maximum of Array?
LeetCode 2439. Minimize Maximum of Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2439. Minimize Maximum of Array?
The Python solution on this page runs in O(n \times \log M), where n is the length of the array, and M is the maximum value in the array.
What is the space complexity of LeetCode 2439. Minimize Maximum of Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2439. Minimize Maximum of Array cover?
LeetCode 2439. Minimize Maximum of Array is tagged Greedy, Array, Binary Search, Dynamic Programming and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview