Choose K Elements With Maximum Sum

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.

Example 1
Inputnums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2
Output[80,30,0,80,50]
For each index, the answer is the maximum sum of at most 2 eligible nums2 values whose corresponding nums1 value is smaller.
Example 2
Inputnums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1
Output[0,0,0,0]
Since all elements in nums1 are equal, no indices satisfy nums1[j] < nums1[i] for any i, resulting in 0 for all positions.

Constraints

  • n == nums1.length == nums2.length
  • 1 <= n <= 10^5
  • 1 <= nums1[i], nums2[i] <= 10^6
  • 1 <= k <= n

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate