You are given an integer array nums
and an integer k
. Return the subsequence of nums
that has the largest sum and is of length k
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
nums
?
nums
can be positive, negative or zero.k
be greater than the length of nums
?
k
will always be less than or equal to the length of nums
.nums
contain duplicate values?
nums
can contain duplicate values.nums
is empty?
k <= len(nums)
, so this scenario shouldn’t occur.heapq
can be helpful here.import heapq
def maxSubsequence(nums, k):
# Create a list of tuples (value, index).
enumerated_nums = [(num, i) for i, num in enumerate(nums)]
# Get the k largest elements along with their indices using a heap.
largest_k = heapq.nlargest(k, enumerated_nums, key=lambda x: x[0])
# Sort these k elements by their original indices to maintain the order.
largest_k.sort(key=lambda x: x[1])
# Extract the values from the sorted tuples.
return [num for num, _ in largest_k]
# Example usage:
nums = [3, 4, 3, 3]
k = 2
print(maxSubsequence(nums, k)) # Output: [4, 3]
nums
.heapq.nlargest
, this step takes O(n log k).The overall time complexity is dominated by the heapq.nlargest
operation, i.e., O(n log k)
.
By following this approach, we ensure that we are efficiently finding the required subsequence while maintaining the original order of elements.
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?