Max sum path in two arrays

Last Updated : 28 Apr, 2026

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.

Try It Yourself
redirect icon

Using Two Pointers and Prefix Sum Traversal - O(m log m + n log n) Time and O(1) Space

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:

  • Initialize variables, result, sum1, sum2. 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 ar1[] and ar2[] respectively. These sums are between two common points.
  • Now run a loop to traverse elements of both arrays. While traversing compare current elements of array 1 and array 2 in the following order.
    • If current element of array 1 is smaller than current element of array 2, then update sum1, else if current element of array 2 is smaller, then update sum2.
    • If the current element of array 1 and array 2 are same, then take the maximum of sum1 and sum2 and add it to the result. Also add the common element to the result.
    • This step can be compared to the merging of two sorted arrays, If the smallest element of the two current array indices is processed then it is guaranteed that if there is any common element it will be processed together. So the sum of elements between two common elements can be processed.

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.


C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int maxPathSum(vector<int> &arr1, vector<int> &arr2) {
    sort(arr1.begin(), arr1.end());
    sort(arr2.begin(), arr2.end());

    int i = 0, j = 0;
    int m = arr1.size(), n = arr2.size();

    long long 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) + arr1[i];
            sum1 = 0;
            sum2 = 0;
            i++;
            j++;
        }
    }

    while (i < m) sum1 += arr1[i++];
    while (j < n) sum2 += arr2[j++];

    result += max(sum1, sum2);

    return (int)result;
}

int main() {
    vector<int> arr1 = {2, 3, 7, 10, 12, 15, 30, 34};
    vector<int> arr2 = {1, 5, 7, 8, 10, 15, 16, 19};

    cout << maxPathSum(arr1, arr2);
    return 0;
}
Java
import java.util.*;

class GFG {

    static int maxPathSum(int[] arr1, int[] arr2) {

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        int i = 0, j = 0;
        int m = arr1.length, n = arr2.length;

        long result = 0, sum1 = 0, sum2 = 0;

        while (i < m && j < n) {

            // Add smaller elements to respective sums
            if (arr1[i] < arr2[j]) {
                sum1 += arr1[i++];
            }
            else if (arr1[i] > arr2[j]) {
                sum2 += arr2[j++];
            }

            // Common element found
            else {
                result += Math.max(sum1, sum2) + arr1[i];
                sum1 = 0;
                sum2 = 0;
                i++;
                j++;
            }
        }

        // Add remaining elements
        while (i < m) sum1 += arr1[i++];
        while (j < n) sum2 += arr2[j++];

        result += Math.max(sum1, sum2);

        return (int) result;
    }

    public static void main(String[] args) {
        int[] arr1 = {2, 3, 7, 10, 12, 15, 30, 34};
        int[] arr2 = {1, 5, 7, 8, 10, 15, 16, 19};

        System.out.println(maxPathSum(arr1, arr2));
    }
}
Python
def maxPathSum(arr1, arr2):
    arr1.sort()
    arr2.sort()

    i = j = 0
    m, n = len(arr1), len(arr2)

    result = 0
    sum1 = sum2 = 0

    while i < m and j < n:
        if arr1[i] < arr2[j]:
            sum1 += arr1[i]
            i += 1
        elif arr1[i] > arr2[j]:
            sum2 += arr2[j]
            j += 1
        else:
            # Common element
            result += max(sum1, sum2) + arr1[i]
            sum1 = sum2 = 0
            i += 1
            j += 1

    # Remaining elements
    while i < m:
        sum1 += arr1[i]
        i += 1

    while j < n:
        sum2 += arr2[j]
        j += 1

    result += max(sum1, sum2)

    return result


# Example
arr1 = [2, 3, 7, 10, 12, 15, 30, 34]
arr2 = [1, 5, 7, 8, 10, 15, 16, 19]

print(maxPathSum(arr1, arr2))
C#
using System;

class GFG {

    static int MaxPathSum(int[] arr1, int[] arr2) {

        Array.Sort(arr1);
        Array.Sort(arr2);

        int i = 0, j = 0;
        int m = arr1.Length, n = arr2.Length;

        long 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 += Math.Max(sum1, sum2) + arr1[i];
                sum1 = 0;
                sum2 = 0;
                i++;
                j++;
            }
        }

        while (i < m) sum1 += arr1[i++];
        while (j < n) sum2 += arr2[j++];

        result += Math.Max(sum1, sum2);

        return (int)result;
    }

    static void Main() {
        int[] arr1 = {2, 3, 7, 10, 12, 15, 30, 34};
        int[] arr2 = {1, 5, 7, 8, 10, 15, 16, 19};

        Console.WriteLine(MaxPathSum(arr1, arr2));
    }
}
JavaScript
function maxPathSum(arr1, arr2) {

    arr1.sort((a, b) => a - b);
    arr2.sort((a, b) => a - b);

    let i = 0, j = 0;
    let m = arr1.length, n = arr2.length;

    let 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 {
            // Common element
            result += Math.max(sum1, sum2) + arr1[i];
            sum1 = 0;
            sum2 = 0;
            i++;
            j++;
        }
    }

    while (i < m) sum1 += arr1[i++];
    while (j < n) sum2 += arr2[j++];

    result += Math.max(sum1, sum2);

    return result;
}

// Example
let arr1 = [2, 3, 7, 10, 12, 15, 30, 34];
let arr2 = [1, 5, 7, 8, 10, 15, 16, 19];

console.log(maxPathSum(arr1, arr2));

Output
122
Comment