#2809

Minimum Time to Make Array Sum At Most x

Hard
ArrayDynamic ProgrammingSortingGreedySorting
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages sorting and a greedy approach. By prioritizing which indices to set to zero based on their increment rates, we can minimize the time needed to achieve the target sum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Pair each element of nums1 with its corresponding element in nums2 and sort these pairs based on the values in nums2 in descending order.
  2. 2Step 2: Initialize a variable to track the current sum of nums1 and the time taken.
  3. 3Step 3: Iterate through the sorted pairs, incrementing the time and adjusting the current sum until it is less than or equal to x.
solution.py12 lines
1def minTime(nums1, nums2, x):
2    n = len(nums1)
3    current_sum = sum(nums1)
4    pairs = sorted(zip(nums1, nums2), key=lambda p: p[1])
5    time = 0
6    for i in range(n):
7        if current_sum <= x:
8            return time
9        current_sum += pairs[i][1]
10        current_sum -= pairs[i][0]
11        time += 1
12    return time if current_sum <= x else -1

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the pairs of nums1 and nums2.

  • 1Setting an index to zero should be done in the order of the increment rates to minimize the overall time.
  • 2The sum of nums1 can only be reduced by setting elements to zero, so careful selection is crucial.

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