Given an integer array nums
and an integer k
, return the maximum sum of k
elements from the array nums
where every element in the array can be chosen only once.
nums
?nums
have?k
elements? (assuming the answer is yes)If nums = [1, 2, 3, 4, 5]
and k = 2
, the maximum sum obtained by choosing exactly 2 elements is 4 + 5 = 9
.
To maximize the sum using exactly k
elements from the array nums
:
nums
array in non-decreasing (ascending) order.k
elements from the sorted array. These will be the last k
elements after sorting.k
largest elements to get the required maximum sum.nums
.Here is the implementation of the described strategy:
def maxSumWithKElements(nums, k):
# Sort the array in ascending order
nums.sort()
# Sum of the largest k elements
return sum(nums[-k:])
# Test case
nums = [1, 2, 3, 4, 5]
k = 2
print(maxSumWithKElements(nums, k)) # Output: 9
nums
to arrange the elements in ascending order.nums[-k:]
, we extract the last k
elements from the sorted array, which are the largest k
elements.This approach ensures that we efficiently compute the maximum sum using exactly k
elements from the given array.
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?