Problem Description
Given a 0-indexed array nums of non-negative integers, you can perform an operation where you choose an index i (1 <= i < n) with nums[i] > 0, then decrease nums[i] by 1 and increase nums[i-1] by 1. The goal is to minimize the maximum value in the array after performing any number of operations.
Key Insights
- The operations only allow shifting value to the left.
- The prefix sums of the array remain invariant; only their distribution can be balanced.
- The minimum possible maximum value is determined by the largest needed average of the prefix, rounded up.
- For each index i, the achievable maximum value must be at least ceil(prefixSum[0...i] / (i + 1)).
Space and Time Complexity
Time Complexity: O(n) - We iterate through the array once. Space Complexity: O(1) - Only a few variables are used.
Solution
We observe that the operations allow "pushing" excess from right to left. This means that the sum of the first i elements (prefix sum) cannot be reduced by any series of operations, though it can be redistributed. To keep all numbers as balanced as possible, the highest value in the prefix will be determined by the ceiling of (sum of the prefix)/(length of the prefix). Thus, for each index, we compute the running sum and take the maximum of ceil(prefixSum / (i + 1)). This maximum will be the minimum achievable maximum value of the array after redistributions.