# Maximum Sum Path in Two Arrays in C++

## Problem statement

Given two sorted arrays such the arrays may have some common elements. Find the sum of the maximum sum path to reach from beginning of any array to end of any of the two arrays. We can switch from one array to another array only at common elements. Note that the common elements do not have to be at same indexes.

Expected time complexity is O(m+n) where m is the number of elements in arr1[] and n is the number of elements in arrs2[]

## Example

If given input is then output is 35
arr1[] = {2, 3, 7, 10, 12}
ar2[] = {1, 5, 7, 8}
(1 + 5 + 7 + 10 + 12) = 35
• 1. We start from first element of arr2 which is 1, then we move to 5, then 7.

• From 7, we switch to ar1 (7 is common) and traverse 10 and 12.

## Algorithm

• The idea is to do something similar to merge process of merge sort. We need to calculate sums of elements between all common points for both arrays. Whenever we see a common point, we compare the two sums and add the maximum of two to the result.

• Initialize result as 0. Also initialize two variables sum1 and sum2 as 0. Here sum1 and sum2 are used to store sum of element in arr1[] and arr2[] respectively. These sums are between two common points

• Now run a loop to traverse elements of both arrays. While traversing compare current elements of arr1[] and arr2[]

• If current element of arr1[] is smaller than current element of arr2[], then update sum1, else if current element of arr2[] is smaller, then update sum

• If current element of arr1[] and arr2[] are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int max(int x, int y){
return (x > y)? x : y;
}
int maxPathSum(int *arr1, int *arr2, int m, int n){
int i = 0, j = 0;
int result = 0, sum1 = 0, sum2 = 0;
while (i < m && j < n) {
if (arr1[i] < arr2[j]) {
sum1 += arr1[i++];
} else if (arr1[i] > arr2[j]) {
sum2 += arr2[j++];
} else {
result += max(sum1, sum2);
sum1 = 0, sum2 = 0;
while (i < m && j < n && arr1[i] == arr2[j]) {
result = result + arr1[i++];
j++;
}
}
}
while (i < m) {
sum1 += arr1[i++];
}
while (j < n) {
sum2 += arr2[j++];
}
result += max(sum1, sum2);
return result;
}
int main(){
int arr1[] = {2, 3, 7, 10, 12};
int arr2[] = {1, 5, 7, 8};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
cout << "Maximum sum path = " << maxPathSum(arr1, arr2, m, n) << endl;
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Maximum sum path = 35

Updated on: 30-Jan-2020

461 Views