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 that1 <= i < n
andnums[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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Binary Search
To solve this problem, we need to minimize the maximum value in the array nums
after performing as many operations as needed. The key insight is that we can use a binary search approach to find the minimum possible value for the maximum element.
Here is the approach:
- Binary Search:
- Use binary search on the possible values of the maximum element, from 0 to the maximum value in
nums
.
- Use binary search on the possible values of the maximum element, from 0 to the maximum value in
- Feasibility Check:
- For each candidate maximum value in the binary search, check if it is possible to reduce the array such that no element exceeds this value.
- Utilize a greedy approach to transfer values from right to left, ensuring the elements do not exceed the candidate maximum.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * log(max(nums))
- The binary search runs in
O(log(max(nums)))
, wheremax(nums)
is the highest value innums
. - The
canReduceToMax
function performs a single pass through the array, making its complexityO(n)
.
- The binary search runs in
- 🧺 Space complexity:
O(1)