Class Solution
-
- All Implemented Interfaces:
public final class Solution3478 - Choose K Elements With Maximum Sum.
Medium
You are given two integer arrays,
nums1andnums2, both of lengthn, along with a positive integerk.For each index
ifrom0ton - 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
answerof sizen, whereanswer[i]represents the result for the corresponding indexi.Example 1:
Input: nums1 = 4,2,1,5,3, nums2 = 10,20,30,40,50, k = 2
Output: 80,30,0,80,50
Explanation:
For
i = 0: Select the 2 largest values fromnums2at indices[1, 2, 4]wherenums1[j] < nums1[0], resulting in50 + 30 = 80.For
i = 1: Select the 2 largest values fromnums2at index[2]wherenums1[j] < nums1[1], resulting in 30.For
i = 2: No indices satisfynums1[j] < nums1[2], resulting in 0.For
i = 3: Select the 2 largest values fromnums2at indices[0, 1, 2, 4]wherenums1[j] < nums1[3], resulting in50 + 30 = 80.For
i = 4: Select the 2 largest values fromnums2at indices[1, 2]wherenums1[j] < nums1[4], resulting in30 + 20 = 50.
Example 2:
Input: nums1 = 2,2,2,2, nums2 = 3,1,2,3, k = 1
Output: 0,0,0,0
Explanation:
Since all elements in
nums1are equal, no indices satisfy the conditionnums1[j] < nums1[i]for anyi, resulting in 0 for all positions.Constraints:
n == nums1.length == nums2.length<code>1 <= n <= 10<sup>5</sup></code>
<code>1 <= nums1i, nums2i<= 10<sup>6</sup></code>
1 <= k <= n