#3478
Choose K Elements With Maximum Sum
MediumArraySortingHeap (Priority Queue)HeapSortingGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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 max heap to efficiently track the largest k values from nums2 as we process each element in sorted order of nums1. This reduces the need for repeated sorting.
⚙️
Algorithm
4 steps- 1Step 1: Pair nums1 and nums2 into a list of tuples and sort them based on nums1.
- 2Step 2: Initialize a max heap to keep track of the largest k values from nums2 as we iterate through the sorted list.
- 3Step 3: For each element in the sorted list, push the corresponding nums2 value into the max heap and, if the heap exceeds size k, pop the smallest element.
- 4Step 4: The sum of the heap gives the desired result for that index in the original order.
solution.py23 lines
1# Full working Python code
2
3import heapq
4
5def choose_k_elements(nums1, nums2, k):
6 n = len(nums1)
7 indexed = sorted(enumerate(nums1), key=lambda x: x[1])
8 result = [0] * n
9 max_heap = []
10 sum_heap = 0
11 j = 0
12 for i in range(n):
13 while j < n and indexed[j][1] < nums1[i]:
14 heapq.heappush(max_heap, nums2[indexed[j][0]])
15 sum_heap += nums2[indexed[j][0]]
16 if len(max_heap) > k:
17 sum_heap -= heapq.heappop(max_heap)
18 j += 1
19 result[i] = sum_heap
20 return result
21
22# Example usage
23print(choose_k_elements([4,2,1,5,3], [10,20,30,40,50], 2))ℹ
Complexity note: The complexity is O(n log n) due to sorting the pairs and maintaining a max heap of size k, which allows for efficient retrieval of the largest k elements.
- 1Sorting helps to efficiently find valid indices without repeated checks.
- 2Using a max heap allows us to maintain the largest k values dynamically as we process elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.