703179. Maximum Sum Path in Two Arrays
Here is the detailed Markdown blog post for the GeeksforGeeks problem "Maximum Sum Path in Two Arrays":
Maximum Sum Path in Two Arrays
Summary
Given two arrays of integers, find the maximum sum path that starts from the first element of each array and ends at the last element of each array. The path can only move from one array to another if the current elements are equal.
Detailed Explanation
The problem requires us to find the maximum sum of a path that alternates between two arrays, starting from the first element of each array and ending at the last element of each array. To solve this problem, we can use dynamic programming.
Here's the step-by-step breakdown:
- Initialize a 2D table
dpwith dimensions(n + 1) x (m + 1), wherenis the length of the first array andmis the length of the second array. - Fill the first row and first column of
dpwith values from the first array and second array, respectively. - Iterate over the table, considering each element at position
(i, j). If the current elements in both arrays are equal (arr1[i] == arr2[j]), we can consider two options:- Move to the next element in the same array (left or up).
- Move to the corresponding element in the other array.
- Calculate the maximum sum for each option and store it in
dp[i][j]. - The maximum sum path is stored in the bottom-right corner of the table (
dp[n][m]).
Here's an ASCII art diagram illustrating the dynamic programming approach:
+---------------+
| arr1[0] | |
+---------------+
| arr2[0] | |
+---------------+
...
| arr1[i-1] | dp[i][j-1] |
+---------------+
| arr2[j-1] | dp[i-1][j] |
+---------------+
...
| arr1[n-1] | dp[n][m-1] |
+---------------+
| arr2[m-1] | dp[n-1][m] |
+---------------+
Time complexity: O(n * m) Space complexity: O(n * m)
Optimized Solutions
Here are optimized solutions in various programming languages:
Java
public class Main {
public static int maxSumPath(int[] arr1, int[] arr2) {
int n = arr1.length;
int m = arr2.length;
int[][] dp = new int[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
dp[i][0] = arr1[i];
}
for (int j = 0; j <= m; j++) {
dp[0][j] = arr2[j];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (arr1[i - 1] == arr2[j - 1]) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}