![]() |
VOOZH | about |
Given two sorted arrays having some elements in common. Find the sum of the maximum sum path to reach from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at common elements.
Note: The common elements do not have to be at the same indexes. And individual arrays have distinct elements only (no repetition within the array).
Examples:
Input: ar1[] = [2, 3, 7, 10, 12], ar2[] = [1, 5, 7, 8]
Output: 35
Explanation: 35 is sum of 1 + 5 + 7 + 10 + 12.
Start from the first element of ar2 which is 1, then move to 5, then 7. From 7 switch to ar1 (as 7 is common) and traverse 10 and 12.Input: ar1[] = [10, 12], ar2 = [5, 7, 9]
Output: 22
Explanation: 22 is the sum of 10 and 12.
Since there is no common element, take all elements from the array with more sum.Input: ar1[] = [2, 3, 7, 10, 12, 15, 30, 34], ar2[] = [1, 5, 7, 8, 10, 15, 16, 19]
Output: 122
Explanation: 122 is sum of 1, 5, 7, 8, 10, 12, 15, 30, 34
Start from the first element of ar2 which is 1, then move to 5, then 7. From 7 switch to ar1 (as 7 is common), then traverse the remaining ar1.
The idea is to do something similar to the merge process of merge sort. This involves calculating the sum of elements between all common points of both arrays. Whenever there is a common point, compare the two sums and add the maximum of two to the result.
Follow the steps below to solve the given problem:
The good thing about this approach is, we cover all elements before reaching a common point. So when we are at a common point, we compare the two sums and decide which one to choose.
122