VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-prefix-sum-possible-by-merging-two-given-arrays/

⇱ Maximum Prefix Sum possible by merging two given arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Prefix Sum possible by merging two given arrays

Last Updated : 23 Jul, 2025

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 : 22
Explanation: Merging the two arrays to generate the sequence {2, 4, -1, -3, 4, 12, 4, -5, -3}. Maximum prefix sum = Sum of {arr[0], ..., arr[6]} = 22.

Input: A[] = {2, 1, 13, 5, 14}, B={-1, 4, -13}
Output: 38
Explanation: Merging the two arrays to generate the sequence {2, 1, -1, 13, 5, 14, -13}. Maximum prefix sum = Sum of {arr[0], ..., arr[6]} = 38.

Naive Approach: The simplest approach is to use Recursion, which can be optimized using Memoization. Follow the steps below to solve the problem:

  • Initialize a map<pair<int, int>, int> dp[] for memorization.
  • Define a recursive function, say maxPresum(x, y) to find the maximum prefix sum:
    • If dp[{x, y}] is already calculated, then return dp[{x, y}].
    • Otherwise, if x==N || y==M, then return 0.
    • Update dp[{x, y}] as dp[{x, y}] = max(dp[{x, y}, a[x]+maxPresum(x+1, y), b[y]+maxPresum(x, y+1)) and then return dp[{x, y}].
  • Print the maximum prefix sum as maxPresum(0, 0).

Below is the implementation of the above approach:


Output: 
38

 

Time Complexity: O(N·M)
Auxiliary Space: O(N*M)

Efficient Approach: The above approach can be optimized based on the observation that the maximum prefix sum is equal to the sum of the maximum prefix sum of arrays A[] and B[]. Follow the steps below to solve the problem:

  • Calculate the maximum prefix sum of array A[] and store it in a variable, say X.
  • Calculate the maximum prefix sum of array B[] and store it in a variable, say Y.
  • Print the sum of X and Y.

Below is the implementation of the above approach: 


Output: 
22

 

Time Complexity: O(M+N)
Auxiliary Space: O(1) 

Comment