#3824

Minimum K to Reduce Array Within Limit

Medium
ArrayBinary SearchBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max(nums)))
Space
O(1)
O(1)
💡

Intuition

Time O(n log(max(nums)))Space O(1)

Use binary search to efficiently find the minimum k that satisfies the condition, leveraging the relationship between k and operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Set low to 1 and high to the maximum value in nums.
  2. 2Step 2: Perform binary search: calculate mid and check if nonPositive(nums, mid) <= mid * mid.
  3. 3Step 3: Adjust low or high based on the condition until low equals high, which gives the minimum k.
solution.py12 lines
1def nonPositive(nums, k):
2    return sum((num + k - 1) // k for num in nums)
3
4def minK(nums):
5    low, high = 1, max(nums)
6    while low < high:
7        mid = (low + high) // 2
8        if nonPositive(nums, mid) <= mid * mid:
9            high = mid
10        else:
11            low = mid + 1
12    return low

Complexity note: Binary search reduces the search space logarithmically while each check takes O(n).

  • 1Binary search optimizes the search for k.
  • 2Understanding operations helps in calculating the required conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.