Salesforce | Onsite | Return N maximum sums of two sorted arrays
Anonymous User
1113

Given two arrays sorted in descending order like so:
A1 - [7, 5, 3, 2]
A2 - [5, 4, 1, 1]

Return an array of the top N maximum sums by adding two elements, one from each array.
For example, the 1st maximum sum of the example above is 7+5 = 12.
The 2nd maximum sum is 7+4 = 11
The 3rd maximum sum is 5+5 = 10

Prompt was to write a function to return an array with the N maximum sum pairs given two descending order arrays. So if N = 3, the function would return [12, 11, 10] because those are the 3 maximum sums between the two arrays. Only one number should be taken from each array.

The solution I came up with was to get the sums of all elements with each other to form a sum array of NM (where N is size of A1 and M is size of A2). Then sort the sum array and return the first N numbers. This has a runtime of (NM) * log(NM).
There's a more efficient solution to this problem, which I couldn't come up with.

Comments (7)