Minimize Maximum of Array - 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.
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,7,1,6]
Output: 5
💡 Note: We can move values leftward: 7→6 (move 1 left), then distribute optimally to get maximum of 5
Example 2 — Already Optimal
$ Input: nums = [10,1]
Output: 10
💡 Note: Cannot reduce the maximum since we can only move from right to left, and leftmost is already maximum
Example 3 — Equal Distribution
$ Input: nums = [4,9,7,4]
Output: 6
💡 Note: Optimal redistribution gives us [6,6,6,6] with maximum 6

Constraints

  • n == nums.length
  • 2 ≤ n ≤ 105
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimize Maximum of Array INPUT nums = [3, 7, 1, 6] 3 i=0 7 i=1 1 i=2 6 i=3 Operation Rules: Choose i where 1 <= i < n Decrease nums[i] by 1 Increase nums[i-1] by 1 Move values LEFT only -1 +1 ALGORITHM STEPS 1 Binary Search Search range [min, max] 2 Check Feasibility Can max be limited to mid? 3 Prefix Sum Check avg(0..i) <= target? 4 Find Minimum Smallest valid max Prefix Sum Calculation i=0: sum=3, avg=3/1=3 i=1: sum=10, avg=10/2=5 i=2: sum=11, avg=11/3=3.67 i=3: sum=17, avg=17/4=4.25 max(ceil(avg)) = ceil(5) = 5 FINAL RESULT 5 Minimum possible maximum One valid final array: 5 5 2 5 [5, 5, 2, 5] - max is 5 Verification: Original: [3, 7, 1, 6] Sum = 3+7+1+6 = 17 Result: [5,5,2,5] sum=17 OK - Valid! Key Insight: The operation can only move values to the LEFT. This means the minimum possible maximum is determined by the ceiling of the average of prefix subarrays. For any prefix [0..i], the max must be at least ceil(sum[0..i]/(i+1)). The answer is the maximum of all these values. Time: O(n) | Space: O(1) - Single pass with prefix sum tracking TutorialsPoint - Minimize Maximum of Array | Optimal Solution (Prefix Average)
Asked in
Google 25 Meta 18 Amazon 15
32.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen