Maximize the Sum Through Two Arrays
You are given two sorted arrays of distinct integers, ARR1
and ARR2
. If there is a common element in both arrays, you can switch from one array to the other.
Your task is to determine a path through the intersections (i.e., common integers) of ARR1
and ARR2
, which results in the maximum possible sum, and return that maximum sum.
Input:
ARR1 = [1, 5, 10, 15, 20] ARR2 = [2, 4, 5, 9, 15]
Output:
56
Example:
For example, in the arrays given, the common elements are 5 and 15.
Start with ARR2
and sum up values until you reach 5 (sum = 11), then switch to ARR1
at 10 and continue until 15 (new sum = 36), then continue with ARR1
alone to add 20 (final sum = 56). The path is 2 -> 4 -> 5 -> 10 -> 15 -> 20.
Input:
The first line contains an integer 'T', representing the number of test cases. Each test case follows:
- The first line includes two space-separated integers, 'N' and 'M', denoting the sizes of 'ARR1' and 'ARR2'.
- The second line contains 'N' space-separated integers denoting the values in 'ARR1'.
- The third line contains 'M' space-separated integers denoting the values in 'ARR2'.
Output:
Output the maximum sum value for each test case on a new line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N, M ≤ 10^4
1 ≤ ARR1[i], ARR2[j] ≤ 10^5
- Time Limit: 1 second
Note:
You do not need to print anything; this has already been managed. Implement the given function to achieve the desired results.
Find the maximum sum by traversing through common elements in two sorted arrays.
Start with the array containing the smaller first common element
Switch arrays at common elements to maximize the sum
Cont...read more
Top Amazon SDE-2 interview questions & answers
Popular interview questions of SDE-2
Top HR questions asked in Amazon SDE-2
Reviews
Interviews
Salaries
Users/Month