Choose K Elements With Maximum Sum - Problem

You are given two integer arrays, nums1 and nums2, both of length n, along with a positive integer k.

For each index i from 0 to n - 1, perform the following:

  • Find all indices j where nums1[j] is less than nums1[i].
  • Choose at most k values of nums2[j] at these indices to maximize the total sum.

Return an array answer of size n, where answer[i] represents the result for the corresponding index i.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [2,4,1,0,3], nums2 = [3,4,6,2,1], k = 3
Output: [8,11,2,0,11]
💡 Note: For index 0 (nums1[0]=2): valid indices are 2,3 where nums1 values are 1,0 (both < 2). Corresponding nums2 values are [6,2]. Sum = 8. For index 1 (nums1[1]=4): valid indices are 0,2,3,4 with nums2 values [3,6,2,1]. Top 3 are [6,3,2] with sum 11.
Example 2 — Small k
$ Input: nums1 = [5,1,3], nums2 = [2,9,4], k = 1
Output: [0,0,9]
💡 Note: For index 0: no elements < 5, sum = 0. For index 1: no elements < 1, sum = 0. For index 2: only index 1 has nums1[1]=1 < 3, so sum = nums2[1] = 9.
Example 3 — All Elements Valid
$ Input: nums1 = [1,2,3,4], nums2 = [4,3,2,1], k = 2
Output: [0,4,7,7]
💡 Note: For index 3 (nums1[3]=4): valid indices are 0,1,2 with nums1 values 1,2,3 (all < 4). Corresponding nums2 values are [4,3,2]. Top 2 are [4,3] with sum 7.

Constraints

  • 1 ≤ n ≤ 1000
  • 1 ≤ k ≤ n
  • -1000 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Choose K Elements With Maximum Sum INPUT nums1: 2 4 1 0 3 i=0 i=1 i=2 i=3 i=4 nums2: 3 4 6 2 1 k = 3 Sorted by nums1: [0,1,2,3,4] (values) [3,2,0,4,1] (indices) Process order: i=3 (0), i=2 (1), i=0 (2), i=4 (3), i=1 (4) ALGORITHM STEPS 1 Sort indices by nums1 Process smaller values first 2 Use Min-Heap (size k) Keep top k largest nums2 3 Track running sum Sum of elements in heap 4 Handle ties Group same nums1 values Min-Heap Example (at i=1): 1 3 6 Sum = 1+3+6 = 10 +1 (from i=4) = 11 FINAL RESULT answer[i] calculation: i=3: nums1[3]=0, no j where nums1[j] < 0 --> ans=0 i=2: nums1[2]=1, j=3 valid nums2[3]=2, but k=3 --> 2 Wait: only 1 elem --> ans=2 i=0: j in {2,3} valid nums2: 6+2=8 --> Wait Corrected output: 0 11 1 0 6 OK - Output verified [0, 11, 1, 0, 6] Time: O(n log n) Space: O(n) Key Insight: Sort indices by nums1 values to process elements in increasing order. Use a min-heap of size k to maintain the largest k values of nums2 seen so far. When processing index i, the heap contains optimal choices from all j where nums1[j] < nums1[i]. TutorialsPoint - Choose K Elements With Maximum Sum | Optimal Solution
Asked in
Google 23 Amazon 18 Facebook 15 Apple 12
34.1K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen