Maximum Sum Path in Two Arrays
Last Updated :
23 Jul, 2025
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.
Maximum Sum Path in Two Arrays using Merge: This approach is based on the following idea:
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.
Illustration:
Input: arr1[] = {2, 3, 7, 10, 12}
arr2[] = {1, 5, 7, 8}
Initialise i = 0, j = 0, sum1 = 0, sum2 = 0, result = 0
Step - 1: arr1[i] > arr2[j]
sum2 = sum2 + arr2[j] = 0 + 1 = 1
j = j + 1 = 1
Step - 2: arr1[i] < arr2[j]
sum1 = sum1 + arr1[i] = 0 + 2 = 2
i = i + 1 = 1
Step - 3: arr1[i] < arr2[j]
sum1 = sum1 + arr1[i] = 2 + 3 = 5
i = i + 1 = 2
Step - 4: arr1[i] > arr2[j]
sum2 = sum2 + arr2[j] = 1 + 5 = 6
j = j + 1 = 2
Step - 5: arr1[i] == arr2[j]
result = result + maximum(sum1, sum2) + arr1[i] = 0 + max(5, 6) + 7 = 13
sum1 = 0, sum2 = 0
i = i + 1 = 3
j = j + 1 = 3
Step - 6: arr1[i] > arr2[j]
sum2 = sum2 + arr2[j] = 0 + 8 = 8
j = j + 1 = 4
Step - 7: sum1 = sum1 + arr1[i] = 0 + 10 = 10
i = i + 1 = 4
Step - 8: sum1 = sum1 + arr1[i] = 10 + 12 = 22
i = i + 1 = 5
Step - 9: result = result + max(sum1, sum2) = 13 + max(10, 22) = 35
Hence, maximum sum path is 35.
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 2are 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.
Below is the implementation of the above code:
C++
// C++ program to find maximum sum path
#include <iostream>
using namespace std;
// Utility function to find maximum of two integers
int max(int x, int y) { return (x > y) ? x : y; }
// This function returns the sum of elements on maximum path
// from beginning to end
int maxPathSum(int ar1[], int ar2[], int m, int n)
{
// initialize indexes for ar1[] and ar2[]
int i = 0, j = 0;
// Initialize result and current sum through ar1[] and
// ar2[].
int result = 0, sum1 = 0, sum2 = 0;
// Below 3 loops are similar to merge in merge sort
while (i < m && j < n) {
// Add elements of ar1[] to sum1
if (ar1[i] < ar2[j])
sum1 += ar1[i++];
// Add elements of ar2[] to sum2
else if (ar1[i] > ar2[j])
sum2 += ar2[j++];
else // we reached a common point
{
// Take the maximum of two sums and add to
// result
// Also add the common element of array, once
result += max(sum1, sum2) + ar1[i];
// Update sum1 and sum2 for elements after this
// intersection point
sum1 = 0;
sum2 = 0;
// update i and j to move to next element of
// each array
i++;
j++;
}
}
// Add remaining elements of ar1[]
while (i < m)
sum1 += ar1[i++];
// Add remaining elements of ar2[]
while (j < n)
sum2 += ar2[j++];
// Add maximum of two sums of remaining elements
result += max(sum1, sum2);
return result;
}
// Driver code
int main()
{
int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 };
int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 };
int m = sizeof(ar1) / sizeof(ar1[0]);
int n = sizeof(ar2) / sizeof(ar2[0]);
// Function call
cout << "Maximum sum path is "
<< maxPathSum(ar1, ar2, m, n);
return 0;
}
Java
// JAVA program to find maximum sum path
class MaximumSumPath {
// Utility function to find maximum of two integers
int max(int x, int y) { return (x > y) ? x : y; }
// This function returns the sum of elements on maximum
// path from beginning to end
int maxPathSum(int ar1[], int ar2[], int m, int n)
{
// initialize indexes for ar1[] and ar2[]
int i = 0, j = 0;
// Initialize result and current sum through ar1[]
// and ar2[].
int result = 0, sum1 = 0, sum2 = 0;
// Below 3 loops are similar to merge in merge sort
while (i < m && j < n) {
// Add elements of ar1[] to sum1
if (ar1[i] < ar2[j])
sum1 += ar1[i++];
// Add elements of ar2[] to sum2
else if (ar1[i] > ar2[j])
sum2 += ar2[j++];
// we reached a common point
else {
// Take the maximum of two sums and add to
// result
// Also add the common element of array,
// once
result += max(sum1, sum2) + ar1[i];
// Update sum1 and sum2 for elements after
// this intersection point
sum1 = 0;
sum2 = 0;
// update i and j to move to next element of
// each array
i++;
j++;
}
}
// Add remaining elements of ar1[]
while (i < m)
sum1 += ar1[i++];
// Add remaining elements of ar2[]
while (j < n)
sum2 += ar2[j++];
// Add maximum of two sums of remaining elements
result += max(sum1, sum2);
return result;
}
// Driver code
public static void main(String[] args)
{
MaximumSumPath sumpath = new MaximumSumPath();
int ar1[] = { 2, 3, 7, 10, 12, 15, 30, 34 };
int ar2[] = { 1, 5, 7, 8, 10, 15, 16, 19 };
int m = ar1.length;
int n = ar2.length;
// Function call
System.out.println(
"Maximum sum path is :"
+ sumpath.maxPathSum(ar1, ar2, m, n));
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to find maximum sum path
# This function returns the sum of elements on maximum path from
# beginning to end
def maxPathSum(ar1, ar2, m, n):
# initialize indexes for ar1[] and ar2[]
i, j = 0, 0
# Initialize result and current sum through ar1[] and ar2[]
result, sum1, sum2 = 0, 0, 0
# Below 3 loops are similar to merge in merge sort
while (i < m and j < n):
# Add elements of ar1[] to sum1
if ar1[i] < ar2[j]:
sum1 += ar1[i]
i += 1
# Add elements of ar2[] to sum2
elif ar1[i] > ar2[j]:
sum2 += ar2[j]
j += 1
else: # we reached a common point
# Take the maximum of two sums and add to result
result += max(sum1, sum2) + ar1[i]
# update sum1 and sum2 to be considered fresh for next elements
sum1 = 0
sum2 = 0
# update i and j to move to next element in each array
i += 1
j += 1
# Add remaining elements of ar1[]
while i < m:
sum1 += ar1[i]
i += 1
# Add remaining elements of b[]
while j < n:
sum2 += ar2[j]
j += 1
# Add maximum of two sums of remaining elements
result += max(sum1, sum2)
return result
# Driver code
ar1 = [2, 3, 7, 10, 12, 15, 30, 34]
ar2 = [1, 5, 7, 8, 10, 15, 16, 19]
m = len(ar1)
n = len(ar2)
# Function call
print("Maximum sum path is", maxPathSum(ar1, ar2, m, n))
# This code is contributed by __Devesh Agrawal__
C#
// C# program for Maximum Sum Path in
// Two Arrays
using System;
class GFG {
// Utility function to find maximum
// of two integers
static int max(int x, int y) { return (x > y) ? x : y; }
// This function returns the sum of
// elements on maximum path from
// beginning to end
static int maxPathSum(int[] ar1, int[] ar2, int m,
int n)
{
// initialize indexes for ar1[]
// and ar2[]
int i = 0, j = 0;
// Initialize result and current
// sum through ar1[] and ar2[].
int result = 0, sum1 = 0, sum2 = 0;
// Below 3 loops are similar to
// merge in merge sort
while (i < m && j < n) {
// Add elements of ar1[] to sum1
if (ar1[i] < ar2[j])
sum1 += ar1[i++];
// Add elements of ar2[] to sum2
else if (ar1[i] > ar2[j])
sum2 += ar2[j++];
// we reached a common point
else {
// Take the maximum of two sums and add to
// result
// Also add the common element of array,
// once
result += max(sum1, sum2) + ar1[i];
// Update sum1 and sum2 for elements after
// this intersection point
sum1 = 0;
sum2 = 0;
// update i and j to move to next element of
// each array
i++;
j++;
}
}
// Add remaining elements of ar1[]
while (i < m)
sum1 += ar1[i++];
// Add remaining elements of ar2[]
while (j < n)
sum2 += ar2[j++];
// Add maximum of two sums of
// remaining elements
result += max(sum1, sum2);
return result;
}
// Driver code
public static void Main()
{
int[] ar1 = { 2, 3, 7, 10, 12, 15, 30, 34 };
int[] ar2 = { 1, 5, 7, 8, 10, 15, 16, 19 };
int m = ar1.Length;
int n = ar2.Length;
// Function call
Console.Write("Maximum sum path is :"
+ maxPathSum(ar1, ar2, m, n));
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// Javascript program to find maximum sum path
// Utility function to find maximum of two integers
function max(x, y)
{
return (x > y) ? x : y;
}
// This function returns the sum of elements
// on maximum path from beginning to end
function maxPathSum(ar1, ar2, m, n)
{
// Initialize indexes for ar1[] and ar2[]
let i = 0, j = 0;
// Initialize result and current sum
// through ar1[] and ar2[].
let result = 0, sum1 = 0, sum2 = 0;
// Below3 loops are similar to
// merge in merge sort
while (i < m && j < n)
{
// Add elements of ar1[] to sum1
if (ar1[i] < ar2[j])
sum1 += ar1[i++];
// Add elements of ar2[] to sum2
else if (ar1[i] > ar2[j])
sum2 += ar2[j++];
// We reached a common point
else
{
// Take the maximum of two sums and add to
// result
//Also add the common element of array, once
result += Math.max(sum1, sum2) + ar1[i];
// Update sum1 and sum2 for elements after this
// intersection point
sum1 = 0;
sum2 = 0;
//update i and j to move to next element of each array
i++;
j++;
}
}
// Add remaining elements of ar1[]
while (i < m)
sum1 += ar1[i++];
// Add remaining elements of ar2[]
while (j < n)
sum2 += ar2[j++];
// Add maximum of two sums of
// remaining elements
result += Math.max(sum1, sum2);
return result;
}
// Driver code
let ar1 = [ 2, 3, 7, 10, 12, 15, 30, 34 ];
let ar2 = [ 1, 5, 7, 8, 10, 15, 16, 19 ];
let m = ar1.length;
let n = ar2.length;
// Function call
document.write("Maximum sum path is " +
maxPathSum(ar1, ar2, m, n));
// This code is contributed by Mayank Tyagi
</script>
PHP
<?php
// PHP Program to find Maximum Sum
// Path in Two Arrays
// This function returns the sum of
// elements on maximum path
// from beginning to end
function maxPathSum($ar1, $ar2, $m, $n)
{
// initialize indexes for
// ar1[] and ar2[]
$i = 0;
$j = 0;
// Initialize result and
// current sum through ar1[]
// and ar2[].
$result = 0;
$sum1 = 0;
$sum2 = 0;
// Below 3 loops are similar
// to merge in merge sort
while ($i < $m and $j < $n)
{
// Add elements of
// ar1[] to sum1
if ($ar1[$i] < $ar2[$j])
$sum1 += $ar1[$i++];
// Add elements of
// ar2[] to sum2
else if ($ar1[$i] > $ar2[$j])
$sum2 += $ar2[$j++];
// we reached a
// common point
else
{
// Take the maximum of two sums and add to
// result
//Also add the common element of array, once
$result += max($sum1, $sum2) + $ar1[$i];
// Update sum1 and sum2 for elements after this
// intersection point
$sum1 = 0;
$sum2 = 0;
//update i and j to move to next element of each array
$i++;
$j++;
}
}
// Add remaining elements of ar1[]
while ($i < $m)
$sum1 += $ar1[$i++];
// Add remaining elements of ar2[]
while ($j < $n)
$sum2 += $ar2[$j++];
// Add maximum of two sums
// of remaining elements
$result += max($sum1, $sum2);
return $result;
}
// Driver Code
$ar1 = array(2, 3, 7, 10, 12, 15, 30, 34);
$ar2 = array(1, 5, 7, 8, 10, 15, 16, 19);
$m = count($ar1);
$n = count($ar2);
// Function call
echo "Maximum sum path is "
, maxPathSum($ar1, $ar2, $m, $n);
// This code is contributed by anuj_67.
?>
OutputMaximum sum path is 122
Time complexity: O(m+n). In every iteration of while loops, an element from either of the two arrays is processed. There are total m + n elements. Therefore, the time complexity is O(m+n).
Auxiliary Space: O(1), Any extra space is not required, so the space complexity is constant.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem