Maximum sum combination from two arrays
Last Updated :
19 Apr, 2023
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}
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++
// CPP program to maximum sum
// combination from two arrays
#include <bits/stdc++.h>
using namespace std;
// Function to maximum sum
// combination from two arrays
int 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 code
int 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
// Java program to maximum sum
// combination from two arrays
class GFG
{
// Function to maximum sum
// combination from two arrays
static 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 code
public 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
# Python3 program to maximum sum
# combination from two arrays
# Function to maximum sum
# combination from two arrays
def 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 code
if __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#
// C# program to maximum sum
// combination from two arrays
using System;
class GFG
{
// Function to maximum sum
// combination from two arrays
static 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 code
public 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..
JavaScript
<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>
Time Complexity: O(N), where N is the length of the given arrays.
Auxiliary Space: O(N)
Efficient approach : Space optimization O(1)
To optimize the space complexity since we only need to access the values of dp[i] and dp[i-1], we can just use variables to store these values instead of an entire array. This way, the space complexity will be reduced from O(N) to O(1)
Implementation Steps:
- Initialize prev1 and prev2 with the first elements of arr1 and arr2 respectively.
- Create two variables curr1 and curr2.
- Use a loop to iterate over the arrays from index 1 to n-1.
- Update prev1 and prev2 to curr1 and curr2 respectively for further iterations.
- Return the maximum of prev1 and prev2 as the maximum sum combination from the two arrays.
Implementation :
C++
#include <bits/stdc++.h>
using namespace std;
// Function to maximum sum combination from two arrays
int Max_Sum(int arr1[], int arr2[], int n)
{
// To store dp value
int prev1 = arr1[0], prev2 = arr2[0];
int curr1, curr2;
// For loop to calculate the value of dp
for (int i = 1; i < n; i++)
{
curr1 = max(prev1, prev2 + arr1[i]);
curr2 = max(prev2, prev1 + arr2[i]);
// assigning values for further iteration
prev1 = curr1;
prev2 = curr2;
}
// Return the required answer
return max(prev1, prev2);
}
// Driver code
int 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
import java.util.*;
public class Main
{
// Function to maximum sum combination from two arrays
static int Max_Sum(int[] arr1, int[] arr2, int n)
{
// To store dp value
int prev1 = arr1[0], prev2 = arr2[0];
int curr1, curr2;
// For loop to calculate the value of dp
for (int i = 1; i < n; i++) {
curr1 = Math.max(prev1, prev2 + arr1[i]);
curr2 = Math.max(prev2, prev1 + arr2[i]);
// assigning values for further iteration
prev1 = curr1;
prev2 = curr2;
}
// Return the required answer
return Math.max(prev1, prev2);
}
// Driver code
public 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));
}
}
Python3
def Max_Sum(arr1, arr2, n):
# To store dp value
prev1 = arr1[0]
prev2 = arr2[0]
curr1 = 0
curr2 = 0
# For loop to calculate the value of dp
for i in range(1, n):
curr1 = max(prev1, prev2 + arr1[i])
curr2 = max(prev2, prev1 + arr2[i])
# assigning values for further iteration
prev1 = curr1
prev2 = curr2
# Return the required answer
return max(prev1, prev2)
# Driver code
arr1 = [9, 3, 5, 7, 3]
arr2 = [5, 8, 1, 4, 5]
n = len(arr1)
# Function call
print(Max_Sum(arr1, arr2, n))
C#
using System;
class MainClass {
// Function to maximum sum combination from two arrays
public static int Max_Sum(int[] arr1, int[] arr2, int n)
{
// To store dp value
int prev1 = arr1[0], prev2 = arr2[0];
int curr1, curr2;
// For loop to calculate the value of dp
for (int i = 1; i < n; i++) {
curr1 = Math.Max(prev1, prev2 + arr1[i]);
curr2 = Math.Max(prev2, prev1 + arr2[i]);
// assigning values for further iteration
prev1 = curr1;
prev2 = curr2;
}
// Return the required answer
return Math.Max(prev1, prev2);
}
// Driver code
public 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));
}
}
JavaScript
// Function to maximum sum combination from two arrays
function Max_Sum(arr1, arr2, n) {
// To store dp value
let prev1 = arr1[0],
prev2 = arr2[0];
let curr1, curr2;
// For loop to calculate the value of dp
for (let i = 1; i < n; i++) {
curr1 = Math.max(prev1, prev2 + arr1[i]);
curr2 = Math.max(prev2, prev1 + arr2[i]);
// assigning values for further iteration
prev1 = curr1;
prev2 = curr2;
}
// Return the required answer
return Math.max(prev1, prev2);
}
// Driver code
let arr1 = [9, 3, 5, 7, 3];
let arr2 = [5, 8, 1, 4, 5];
let n = arr1.length;
// Function call
console.log(Max_Sum(arr1, arr2, n));
//This code is contributed by sarojmcy2e
Output
29
Time Complexity: O(N), where N is the length of the given arrays.
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read