Minimum K to Reduce Array Within Limit Problem
Description
LeetCode Problem 3824.
You are given a positive integer array nums.
For a positive integer k, define nonPositive(nums, k) as the minimum number of operations needed to make every element of nums non-positive. In one operation, you can choose an index i and reduce nums[i] by k.
Return an integer denoting the minimum value of k such that nonPositive(nums, k) <= k^2.
Example 1:
Input: nums = [3,7,5]
Output: 3
Explanation:
When k = 3, nonPositive(nums, k) = 6 <= k^2.
- Reduce nums[0] = 3 one time. nums[0] becomes 3 - 3 = 0.
- Reduce nums[1] = 7 three times. nums[1] becomes 7 - 3 - 3 - 3 = -2.
- Reduce nums[2] = 5 two times. nums[2] becomes 5 - 3 - 3 = -1.
Example 2:
Input: nums = [1]
Output: 1
Explanation:
When k = 1, nonPositive(nums, k) = 1 <= k^2.
- Reduce nums[0] = 1 one time. nums[0] becomes 1 - 1 = 0.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Binary Search
A larger k can only make the condition easier to meet: each element needs no more operations, and k^2 grows. So the condition is monotonic in k and we can binary search for the smallest k that satisfies it.
Search k in [1, 10^5]. For a candidate mid, compute nonPositive(nums, mid) as the sum of ceil(x / mid) over all elements and compare it with mid * mid. If it fits, the answer is at most mid (move the right end); otherwise move the left end past mid.
Complexity: O(n log M) time and O(1) extra space, where n is the length of nums and M = 10^5 is the search range.
class Solution:
def minimumK(self, nums: List[int]) -> int:
def check(k: int) -> bool:
t = 0
for x in nums:
t += (x + k - 1) // k
return t <= k * k
l, r = 1, 10**5
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l