Given an array of integers nums
and a threshold value target
, we need to find the minimum number of elements we need to add up from nums
to exceed the target
value. If it is not possible to exceed the target
, return -1.
current_sum
to 0 and a counter to keep track of the number of elements added.current_sum
and increment the counter until current_sum
exceeds the target
.current_sum
does not exceed the target
, return -1.from typing import List
def min_operations(nums: List[int], target: int) -> int:
nums.sort(reverse=True) # sort the array in descending order
current_sum = 0
count = 0
for num in nums:
current_sum += num
count += 1
if current_sum > target:
return count
return -1 # if we exhaust the array and never exceed the target
# Example usage:
# nums = [1, 2, 3, 4, 5]
# target = 11
# Expected output: 3 (we can pick 5, 4, and 3 to exceed 11)
print(min_operations([1, 2, 3, 4, 5], 11))
Let’s take the sample array [1, 2, 3, 4, 5]
and the target 11
.
[5, 4, 3, 2, 1]
current_sum
(12) now exceeds the target
(11), we return the count, which is 3.This approach ensures we find the minimal number of operations required to exceed the target efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?