700241. Max sum path in two arrays

Medium

Max sum path in two arrays

Summary

The problem is to find the maximum sum path between two arrays. Given two arrays A and B, each containing non-negative integers, you need to find a sequence of elements from both arrays that adds up to the maximum possible value. This problem requires understanding of dynamic programming concepts and array manipulation techniques.

Detailed Explanation

To solve this problem, we will use dynamic programming to build a 2D table where each cell represents the maximum sum path ending at that point. We start by initializing a 2D table dp with dimensions (m+1) x (n+1) where m and n are the lengths of arrays A and B, respectively.

We iterate through both arrays simultaneously, and for each pair of elements (a, b) from A and B, we calculate the maximum sum path ending at that point. This is done by considering two options: either take the current element from array A or array B, and then recursively find the maximum sum path in the remaining arrays.

The time complexity of this approach is O(mn) where m and n are the lengths of arrays A and B, respectively. The space complexity is also O(mn) for storing the dynamic programming table.

Here's a step-by-step breakdown of the solution:

  1. Initialize a 2D table dp with dimensions (m+1) x (n+1) where m and n are the lengths of arrays A and B, respectively.
  2. Iterate through both arrays simultaneously, considering each pair of elements (a, b) from A and B.
  3. For each pair (a, b), calculate the maximum sum path ending at that point by considering two options:
    • Take the current element a from array A and recursively find the maximum sum path in the remaining arrays.
    • Take the current element b from array B and recursively find the maximum sum path in the remaining arrays.
  4. Store the maximum sum path ending at each point in the dynamic programming table dp.
  5. The maximum sum path is stored in the last cell of the dynamic programming table, which corresponds to the maximum sum path between the two arrays.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxSumPath(int[] A, int[] B) {
    int m = A.length;
    int n = B.length;
    int[][] dp = new int[m+1][n+1];

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0) {
                dp[i][j] = B[j];
            } else if (j == 0) {
                dp[i][j] = A[i-1];
            } else {
                dp[i][j] = Math.max(A[i-1], B[j-1]) + dp[i-1][j-1];
            }
        }
    }

    return dp[m][n];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.