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
jwherenums1[j]is less thannums1[i]. - Choose at most
kvalues ofnums2[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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code