oneby7

Heaps Top K

413. Maximum Sum Combinations

Medium

You are given two arrays of integers, a and b, both of length n, and an integer k.

Take one value from a and one value from b and add them. There are n2 such sums, one for each pair of positions (i, j), and each is a[i] + b[j]. Return the k largest of these sums, from largest to smallest.

Each pair of positions gives its own sum. When two different pairs give the same sum, both count, so the answer can hold the same value more than once.

Example 1

Input: a = [3, 8, 5], b = [6, 1, 4], k = 5

Output: [14,12,11,9,9]

Explanation: The largest sums are 8 + 6 = 14, 8 + 4 = 12 and 5 + 6 = 11. Three pairs give 9: 8 + 1, 5 + 4 and 3 + 6. Two of them fill the last two places.

Example 2

Input: a = [-4, 0, -7], b = [-2, -9, 3], k = 3

Output: [3,-1,-2]

Explanation: The three largest sums are 0 + 3 = 3, -4 + 3 = -1 and 0 + (-2) = -2.

Example 3

Input: a = [2, 2], b = [5, 5], k = 4

Output: [7,7,7,7]

Explanation: All four pairs of positions give 7, and each of them counts.

Check your understanding

Work out the answer for this input before you write any code.

a = [4, 2, 1], b = [3, 3, 0], k = 4

Constraints

  • a.length == b.length == n
  • 1 ≤ n ≤ 105
  • -109 ≤ a[i], b[i] ≤ 109
  • 1 ≤ k ≤ min(n2, 105)

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.