Maximum sum combination from two arrays - GeeksforGeeks

04 Sep, 2021
Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both the 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 above-chosen numbers. 
Examples: 
Input : arr1[] = {9, 3, 5, 7, 3}, arr2[] = {5, 8, 1, 4, 5} Output : 29 Select first, third and fifth element from the first array. Select the second and fourth element from the second array. 
Input : arr1[] = {1, 2, 9}, arr2[] = {10, 1, 1} Output : 19 Select last element from the first array and first element from the second array. 
Approach : This problem is based on dynamic programming. 
Let dp(i, 1) be the maximum sum of the newly selected elements if the last element was taken from the position(i-1, 1).
dp(i, 2) is the same but the last element taken has the position (i-1, 2)
dp(i, 3) the same but we didn’t take any element from position i-1
Recursion relations are : 
dp(i, 1)=max(dp (i – 1, 2) + arr(i, 1), dp(i – 1, 3) + arr(i, 1), arr(i, 1) ); dp(i, 2)=max(dp(i – 1, 1) + arr(i, 2 ), dp(i – 1, 3) + arr (i, 2), arr(i, 2)); dp(i, 3)=max(dp(i- 1, 1), dp( i-1, 2) ).
We don’t actually need dp( i, 3), if we update dp(i, 1) as max(dp(i, 1), dp(i-1, 1)) and dp(i, 2) as max(dp(i, 2), dp(i-1, 2)).Thus, dp(i, j) is the maximum total sum of the elements that are selected if the last element was taken from the position (i-1, 1) or less. The same with dp(i, 2). Therefore the answer to the above problem is max(dp(n, 1), dp(n, 2)).
Below is the implementation of the above approach :  
C++
Java
Python3
C#
Javascript
// CPP program to maximum sum// combination from two arrays#include <bits/stdc++.h>using namespace std;  // Function to maximum sum// combination from two arraysint Max_Sum(int arr1[], int arr2[], int n){    // To store dp value    int dp[n][2];         // For loop to calculate the value of dp    for (int i = 0; i < n; i++)    {        if(i==0)        {            dp[i][0] = arr1[i];            dp[i][1] = arr2[i];            continue;        }                dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i]);       dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i]);    }         // Return the required answer    return max(dp[n-1][0], dp[n-1][1]);} // Driver codeint main(){    int arr1[] = {9, 3, 5, 7, 3};    int arr2[] = {5, 8, 1, 4, 5};     int n = sizeof(arr1) / sizeof(arr1[0]);         // Function call    cout << Max_Sum(arr1, arr2, n);     return 0;}
// Java program to maximum sum// combination from two arraysclass GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int arr1[],                   int arr2[], int n){    // To store dp value    int [][]dp = new int[n][2];         // For loop to calculate the value of dp    for (int i = 0; i < n; i++)    {        if(i == 0)        {            dp[i][0] = arr1[i];            dp[i][1] = arr2[i];            continue;        }                 dp[i][0] = Math.max(dp[i - 1][0],                            dp[i - 1][1] + arr1[i]);        dp[i][1] = Math.max(dp[i - 1][1],                              dp[i - 1][0] + arr2[i]);    }         // Return the required answer    return Math.max(dp[n - 1][0],                    dp[n - 1][1]);} // Driver codepublic static void main(String[] args){    int arr1[] = {9, 3, 5, 7, 3};    int arr2[] = {5, 8, 1, 4, 5};     int n = arr1.length;         // Function call    System.out.println(Max_Sum(arr1, arr2, n));}} // This code is contributed// by PrinciRaj1992
# Python3 program to maximum sum# combination from two arrays # Function to maximum sum# combination from two arraysdef Max_Sum(arr1, arr2, n):         # To store dp value    dp = [[0 for i in range(2)]             for j in range(n)]         # For loop to calculate the value of dp    for i in range(n):        if(i == 0):            dp[i][0] = arr1[i]            dp[i][1] = arr2[i]            continue        else:            dp[i][0] = max(dp[i - 1][0],                           dp[i - 1][1] + arr1[i])            dp[i][1] = max(dp[i - 1][1],                           dp[i - 1][0] + arr2[i])         # Return the required answer    return max(dp[n - 1][0],               dp[n - 1][1]) # Driver codeif __name__ == '__main__':    arr1 = [9, 3, 5, 7, 3]    arr2 = [5, 8, 1, 4, 5]     n = len(arr1)         # Function call    print(Max_Sum(arr1, arr2, n)) # This code is contributed by# Surendra_Gangwar
// C# program to maximum sum// combination from two arraysusing System; class GFG{ // Function to maximum sum// combination from two arraysstatic int Max_Sum(int []arr1,                   int []arr2, int n){    // To store dp value    int [,]dp = new int[n, 2];         // For loop to calculate the value of dp    for (int i = 0; i < n; i++)    {        if(i == 0)        {            dp[i, 0] = arr1[i];            dp[i, 1] = arr2[i];            continue;        }                 dp[i, 0] = Math.Max(dp[i - 1, 0],                            dp[i - 1, 1] + arr1[i]);        dp[i, 1] = Math.Max(dp[i - 1, 1],                            dp[i - 1, 0] + arr2[i]);    }         // Return the required answer    return Math.Max(dp[n - 1, 0],                    dp[n - 1, 1]);} // Driver codepublic static void Main(){    int []arr1 = {9, 3, 5, 7, 3};    int []arr2 = {5, 8, 1, 4, 5};     int n = arr1.Length;         // Function call    Console.WriteLine(Max_Sum(arr1, arr2, n));}} // This code is contributed// by anuj_67..
<script>    // Javascript program to maximum sum combination from two arrays         // Function to maximum sum    // combination from two arrays    function Max_Sum(arr1, arr2, n)    {        // To store dp value        let dp = new Array(n);        for (let i = 0; i < n; i++)        {            dp[i] = new Array(2);            for (let j = 0; j < 2; j++)            {                dp[i][j] = 0;               }        }         // For loop to calculate the value of dp        for (let i = 0; i < n; i++)        {            if(i == 0)            {                dp[i][0] = arr1[i];                dp[i][1] = arr2[i];                continue;            }             dp[i][0] = Math.max(dp[i - 1][0],                                dp[i - 1][1] + arr1[i]);            dp[i][1] = Math.max(dp[i - 1][1],                                  dp[i - 1][0] + arr2[i]);        }         // Return the required answer        return Math.max(dp[n - 1][0],                        dp[n - 1][1]);    }         let arr1 = [9, 3, 5, 7, 3];    let arr2 = [5, 8, 1, 4, 5];       let n = arr1.length;           // Function call    document.write(Max_Sum(arr1, arr2, n)); </script>
29
 
Time Complexity: O(N) 
princiraj1992
vt_m
SURENDRA_GANGWAR
divyesh072019
khushboogoyal499
sumitgumber28
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Linear Search
Queue | Set 1 (Introduction and Array Implementation)
Python | Using 2D arrays/lists the right way
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16