The Wayback Machine - https://web.archive.org/web/20240818165445/https://www.geeksforgeeks.org/maximum-sum-path-across-two-arrays/
Open In App

Maximum Sum Path in Two Arrays

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.
?>

Output
Maximum 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

Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Minimum cost such that path sum is at max K (Target Path Sum)
Given a rooted tree consisting of N vertices. The vertices are numbered from 0 to N-1, and the root is the vertex 0. You are also given a value array Arr: Arr0, Arr1,....., Arrn-1. You can do any of these moves any number of times: Pick any node that is not root cut the edge between it and its parent and connect an edge between this node to the roo
11 min read
Find Sum of pair from two arrays with maximum sum
Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input : arr1[] = {10, 2, 3}, arr2[] = {3, 4, 7} Output : M
6 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows : We can only start with arr[i][M] where 0 &lt;= i &lt;= N.We end the path on the same side, such that we can take exactly 2 left turns.First we calcula
2 min read
Find the maximum path sum between two leaves of a binary tree
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. The maximum sum path may or may not go through the root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 - 1 + 10). Expected time complexity is O(n). If one side of the root is empty, then the
13 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Count of possible arrays from prefix-sum and suffix-sum arrays
Given 2*N integers which are elements of a prefix and suffix array(in shuffled order) of an array of size N, the task is to find the no of possible array's of the size N which can be made from these elements Examples: Input: arr[] = {5, 2, 3, 5} Output: 2 Explanation: 1st array can be : {2, 3} Its prefix array:{2, 5} Its suffix array:{5, 3} 2nd arr
15+ min read
Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: Input: n = 4, k = 2, arr[] = {10, 10, 11, 11 }, brr
8 min read
K maximum sum combinations from two arrays
Given two equally sized arrays (A, B) and N (size of both arrays). A sum combination is made by adding one element from array A and another element of array B. Display the maximum K valid sum combinations from all the possible sum combinations. Examples: Input : A[] : {3, 2} B[] : {1, 4} K : 2 [Number of maximum sum combinations to be printed]Outpu
15 min read
Maximum sum combination from two arrays
Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of the above-chosen numbers. Examples: Input : arr1[] = {9, 3, 5, 7, 3}, arr2[] = {5, 8, 1, 4, 5} Outp
10 min read
Maximum Sum of Products of two arrays by toggling adjacent bits
Given an integer array arr1 and a binary array arr2 of same size, the task is to find the maximum possible sum of products of these arrays, i.e. (arr1[0] * arr2[0]) + (arr1[1] * arr2[1]) + ..... (arr1[N-1] * arr2[N-1]) obtained by toggling any 2 adjacent bits in the array arr2. This toggle can be done infinite number of times.Toggling of 2 adjacent
9 min read
Maximum sum by picking elements from two arrays in order | Set 2
Given two arrays A[] and B[], each of size N, and two integers X and Y denoting the maximum number of elements that can be picked from A[] and B[] respectively, the task is to find the maximum possible sum by selecting N elements in such a way that for any index i, either A[i] or B[i] can be chosen. Note: It is guaranteed that (X + Y) &gt;= N.Examp
10 min read
Maximum Prefix Sum possible by merging two given arrays
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to calculate the maximum prefix sum that can be obtained by merging the two arrays. Examples: Input : A[] = {2, -1, 4, -5}, B[]={4, -3, 12, 4, -3}Output : 22Explanation: Merging the two arrays to generate the sequence {2, 4, -1, -3, 4, 12, 4, -5, -3}. Maximum pref
11 min read
Maximum length of subarray with same sum at corresponding indices from two Arrays
Given two arrays A[] and B[] both consisting of N integers, the task is to find the maximum length of subarray [i, j] such that the sum of A[i... j] is equal to B[i... j]. Examples: Input: A[] = {1, 1, 0, 1}, B[] = {0, 1, 1, 0}Output: 3Explanation: For (i, j) = (0, 2), sum of A[0... 2] = sum of B[0... 2] (i.e, A[0]+A[1]+A[2] = B[0]+B[1]+B[2] =&gt;
6 min read
Maximum difference of prefix sum for all indices of given two Arrays
Given 2 arrays of integers a[] and s[] both of size N. The task is to find the maximum difference of prefix sum for all indices of the given arrays. Examples: Input: N = 5, a[] = {20, 20, 35, 20, 35}, s[] = {21, 31, 34, 41, 14}Output: 32Explanation: After prefix sum the arrays are a[] = {20, 40, 75, 95, 130} and b[] = {21, 52, 86, 127, 141} for S.
4 min read
Maximum elements that can be removed from front of two arrays such that their sum is at most K
Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the removed element must be at most K.Decrease the value
15+ min read
Maximum possible pair sum at most K from two Arrays
Given two arrays arr1[] and arr2[] of sizes N and M and an integer K, the task is to find the maximum possible sum pair from two arrays such that the sum is at most K. Note: You have to take one element from each array. Examples: Input: arr1[] = {5, 4, 1, 2, 3}, arr2[] = {30, 20, 40, 10}, K = 30Output: 25Explanation: Maximum sum of a pair is (20 +
12 min read
Maximum Sum of Products of Two Arrays
Given two arrays A and B of positive integers of the same size N. The task is to find the maximum sum of products of their elements. Each element in A has to be multiplied with exactly one element in B or vice versa such that each element of both the arrays appears exactly once and the sum of the product obtained is maximum. Examples: Input : A[] =
5 min read
Maximum absolute difference between sum of two contiguous sub-arrays
Given an array of integers, find two non-overlapping contiguous sub-arrays such that the absolute difference between the sum of two sub-arrays is maximum. Example: Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output: 16 Two subarrays are [-1, -2, 1, -4] and [2, 8] E
15+ min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array
Given two arrays arr1[] and arr2[] of size N and M respectively, the task is to count the minimum number of swaps required between the two arrays in order to make the sum of the array arr1[] greater than the arr2[]. Examples: Input: arr1[] = {1, 3, 2, 4}, arr2[] = {6, 7, 8}Output: 1Explanation:Swapping arr1[0] with arr2[2] makes the sum of arr1[] e
10 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Find the path from root to a vertex such that all K vertices belongs to this path or 1 distance away
Given a tree consisting of N vertices numbered from 1 to N rooted at vertex 1. You are given Q queries. Each query consists of the set of K distinct vertices vi[1], vi[2],…, vi[K]. The task is to determine if there is a path from the root to some vertex X such that each of the given K vertices either belongs to this path or has the distance 1 to so
10 min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) &gt; Weight(E2) &lt; Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Difference Between Hamiltonian Path and Eulerian Path
The Hamiltonian and Eulerian paths are two significant concepts used to the solve various problems related to the traversal and connectivity of the graphs. Understanding the differences between these two types of the paths is crucial for the designing efficient algorithms and solving the complex graph problems. What is a Hamiltonian Path?Hamiltonia
2 min read
Path with smallest difference between consecutive cells (Path with minimum effort)
Given a 2D array arr[] of size N x M, where arr[i][j] represents the value of cell (i, j). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (n-1, m-1). You can move up, down, left, or right, and you wish to find a path such that the maximum absolute difference in values between two consecutive cells of
14 min read
Print the path common to the two paths from the root to the two given nodes
Given a binary tree with distinct nodes(no two nodes have the same data values). The problem is to print the path common to the two paths from the root to the two given nodes n1 and n2. If either of the nodes are not present then print "No Common Path". Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 n1 = 4, n2 = 8 Output : 1-&gt;2 Path form ro
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg