Maximum Subarray sum of A[] by adding any element of B[] at any end
Last Updated :
23 Jul, 2025
Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it:
- Choose either the leftmost or rightmost element from B[] and add it to any end of A[].
- Delete the element chosen from B[].
Examples:
Input: N = 4, A[] = {72, 23, -56, 80}, M = 2, B[] = {50, 10}
Output: 179
Explanation: First Operation: Get element 50 at first index from B[] and prepend it in A[] to make A[] = {50, 72, 23 -56, 80} and B[] = {10}
Second Operation: Get element 10 at last index from B[] and append it in A[] to make A[] = {50, 72, 23 -56, 80, 10}.
Now, B[] has no elements. The maximum value of sum that can be obtained by perform given operation at most K times is: 179 by subarray (50, 72, 23, -56, 80, 10).
Input: N = 2, A[] = {50, -45}, M = 2, B[] = {90},
Output: 140
Approach: The problem can be solved based on the following idea:
Problem is based on Kadane's Algorithm and Greedy approach. Find maximum subarray sum in A[] using Kadane's Algorithm let's say it as Z. Now there can be three cases for the subarray with maximum sum:
- The subarray has one end at the front: In this case adding the positive elements of B[] at the front of A[] gives the maximum possible subarray sum after the operations.
- The subarray of A[] with sum Z has one end at the end of A[]: Here appending positive elements of B[] to the end of A[] will give maximum sum.
- The subarray with maximum sum lies somewhere in between: In this case the choices are to add the positive elements of B[] to the beginning (say the maximum subarray sum from start becomes P) or to the end (say the maximum subarray sum ending at end is Q). The maximum sum will then be max among Z, P and Q.
Follow the steps given below to solve the problem:
- Create a variable max_sum to store the maximum sub-array sum of X[].
- Add positive elements from B[] to the starting of A[] and find the max subarray sum starting from the beginning of A[].
- Add positive elements from B[] to the end of A[] and find the max subarray sum finishing at the end of A[].
- The maximum of the above three is the required answer.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum possible sum
int maxSum(int a[], int b[], int n, int m)
{
int mx1 = 0, mx2 = 0;
// Function to find the max subarray sum
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
if (tmp < 0) {
tmp = 0;
}
else
mx1 = max(mx1, tmp);
}
// Function to find the maximum subarray sum
// starting from the start
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
mx2 = max(mx2, tmp);
}
// Function to find the maximum subarray sum
// ending at the end
for (int i = n - 1, tmp = 0; i >= 0; i--) {
tmp += a[i];
mx2 = max(mx2, tmp);
}
int ans = 0;
// Sum of the positive elements of B[]
for (int i = 0; i < m; i++) {
if (b[i] > 0)
ans += b[i];
}
// Maximum sum when positive elements are added
// to the start or end and the subarray
// starts from the start or finishes at the end
ans += mx2;
// Return the maximum sum
// among the above three cases
return max(ans, mx1);
}
// Driver code
int main()
{
int A[] = { 72, 23, -56, 80 };
int B[] = { 50, 10 };
int N = sizeof(A) / sizeof(A[0]);
int M = sizeof(B) / sizeof(B[0]);
// Function call
cout << maxSum(A, B, N, M);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
class GFG {
// Function to find the maximum possible sum
static int maxSum(int[] a, int[] b, int n, int m)
{
int mx1 = 0, mx2 = 0;
// Function to find the max subarray sum
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
if (tmp < 0) {
tmp = 0;
}
else {
mx1 = Math.max(mx1, tmp);
}
}
// Function to find the maximum subarray sum
// starting from the start
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
mx2 = Math.max(mx2, tmp);
}
// Function to find the maximum subarray sum
// ending at the end
for (int i = n - 1, tmp = 0; i >= 0; i--) {
tmp += a[i];
mx2 = Math.max(mx2, tmp);
}
int ans = 0;
// Sum of the positive elements of B[]
for (int i = 0; i < m; i++) {
if (b[i] > 0)
ans += b[i];
}
// Maximum sum when positive elements are added
// to the start or end and the subarray
// starts from the start or finishes at the end
ans += mx2;
// Return the maximum sum
// among the above three cases
return Math.max(ans, mx1);
}
public static void main(String[] args)
{
int[] A = { 72, 23, -56, 80 };
int[] B = { 50, 10 };
int N = A.length;
int M = B.length;
// Function call
System.out.print(maxSum(A, B, N, M));
}
}
// This code is contributed by lokeshmvs21.
Python3
# Python code to implement the approach
# function to find the maximum possible sum
def maxSum(a, b, n, m):
mx1, mx2 = 0, 0
# Function to find the max subarray sum
tmp = 0
for i in range(n):
tmp += a[i]
if(tmp < 0):
tmp = 0
else:
mx1 = max(mx1, tmp)
# Function to find the maximum
# subarray sum starting from the start
tmp = 0
for i in range(n):
tmp += a[i]
mx2 = max(mx2, tmp)
# Function to find the maximum
# subarray sum ending at the end
tmp = 0
for i in range(n-1, -1, -1):
tmp += a[i]
mx2 = max(mx2, tmp)
ans = 0
# Sum of the positive elements of B[]
for i in range(m):
if(b[i] > 0):
ans += b[i]
# Maximum sum when positive elements are
# added to the start or end and the subarray
# starts from the start or finishes at the end
ans += mx2
# Return the maximum sum among the above three cases
return max(ans, mx1)
A = [72, 23, -56, 80]
B = [50, 10]
N = len(A)
M = len(B)
# Function call
print(maxSum(A, B, N, M))
# This code is contributed by lokeshmvs21.
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
// Function to find the maximum possible sum
static int maxSum(int[] a, int[] b, int n, int m)
{
int mx1 = 0, mx2 = 0;
// Function to find the max subarray sum
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
if (tmp < 0) {
tmp = 0;
}
else {
mx1 = Math.Max(mx1, tmp);
}
}
// Function to find the maximum subarray sum
// starting from the start
for (int i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
mx2 = Math.Max(mx2, tmp);
}
// Function to find the maximum subarray sum
// ending at the end
for (int i = n - 1, tmp = 0; i >= 0; i--) {
tmp += a[i];
mx2 = Math.Max(mx2, tmp);
}
int ans = 0;
// Sum of the positive elements of B[]
for (int i = 0; i < m; i++) {
if (b[i] > 0)
ans += b[i];
}
// Maximum sum when positive elements are added
// to the start or end and the subarray
// starts from the start or finishes at the end
ans += mx2;
// Return the maximum sum
// among the above three cases
return Math.Max(ans, mx1);
}
public static void Main()
{
int[] A = { 72, 23, -56, 80 };
int[] B = { 50, 10 };
int N = A.Length;
int M = B.Length;
// Function call
Console.WriteLine(maxSum(A, B, N, M));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
// JavaScript code for the above approach
// Function to find the maximum possible sum
function maxSum(a, b, n, m) {
let mx1 = 0, mx2 = 0;
// Function to find the max subarray sum
for (let i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
if (tmp < 0) {
tmp = 0;
}
else
mx1 = Math.max(mx1, tmp);
}
// Function to find the maximum subarray sum
// starting from the start
for (let i = 0, tmp = 0; i < n; i++) {
tmp += a[i];
mx2 = Math.max(mx2, tmp);
}
// Function to find the maximum subarray sum
// ending at the end
for (let i = n - 1, tmp = 0; i >= 0; i--) {
tmp += a[i];
mx2 = Math.max(mx2, tmp);
}
let ans = 0;
// Sum of the positive elements of B[]
for (let i = 0; i < m; i++) {
if (b[i] > 0)
ans += b[i];
}
// Maximum sum when positive elements are added
// to the start or end and the subarray
// starts from the start or finishes at the end
ans += mx2;
// Return the maximum sum
// among the above three cases
return Math.max(ans, mx1);
}
// Driver code
let A = [72, 23, -56, 80];
let B = [50, 10];
let N = A.length;
let M = B.length;
// Function call
console.log(maxSum(A, B, N, M));
// This code is contributed by Potta Lokesh
Time Complexity: O(max(N, M))
Auxiliary Space: O(1)
Another Approach:
- Initialize two pointers, left and right, to the leftmost and rightmost indices of array A[].
Initialize a variable currsum to 0 and maxsum to INT_MIN value.
Iterate through the elements of array B[] and then A[]. - Append all positive elements of B[] to front of A[] and negative to back of A[].
- Append all positive elements of B[] to back of A[] and negative to front of A[]
- Get maxSubArray in both cases and the maximum of those two will be the answer.
- Return maxSum.
C++
#include <bits/stdc++.h>
using namespace std;
int SubArraySum(vector<int>& arr)
{
int maxsum = INT_MIN;
int currsum = 0;
for (int num : arr) {
currsum = max(num, currsum + num);
maxsum = max(maxsum, currsum);
}
return maxsum;
}
int maxSubarraySum(int N, vector<int>& A, int M,
vector<int>& B)
{
int maxsum = INT_MIN;
// Calculate max subarray sum of A
int maxsum_A = SubArraySum(A);
// Initialize left and right pointers
int left = 0, right = N - 1;
// Condition 1: Append all positive elements of B[] to
// front of A[] and negative to back of A[]
while (!B.empty()) {
int front = B.front();
B.erase(B.begin());
if (front >= 0) {
A.insert(A.begin(), front);
}
else {
A.push_back(front);
}
maxsum = max(maxsum, SubArraySum(A));
}
// Reset A to its original state
A.clear();
A = vector<int>(N, 0);
copy(A.begin(), A.end(), back_inserter(A));
// Condition 2: Append all positive elements of B[] to
// back of A[] and negative to front of A[]
while (!B.empty()) {
int back = B.back();
B.pop_back();
if (back >= 0) {
A.push_back(back);
}
else {
A.insert(A.begin(), back);
}
maxsum = max(maxsum, SubArraySum(A));
}
return max(maxsum, maxsum_A);
}
int main()
{
int N = 4;
vector<int> A = { 72, 23, -56, 80 };
int M = 2;
vector<int> B = { 50, 10 };
cout << maxSubarraySum(N, A, M, B)
<< endl; // Output: 179
return 0;
}
Java
import java.util.*;
public class Main {
public static int maxSubArraySum(List<Integer> arr)
{
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int num : arr) {
currentSum = Math.max(num, currentSum + num);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static int maxSubarraySum(int N, List<Integer> A,
int M, List<Integer> B)
{
int maxSum = Integer.MIN_VALUE;
// Calculate max subarray sum of A
int maxSumA = maxSubArraySum(A);
// Initialize left and right pointers
int left = 0;
int right = N - 1;
// Condition 1: Append all positive elements of B[]
// to front of A[] and negative to back of A[]
while (!B.isEmpty()) {
int front = B.get(0);
B.remove(0);
if (front >= 0) {
A.add(0, front);
}
else {
A.add(front);
}
maxSum = Math.max(maxSum, maxSubArraySum(A));
}
// Reset A to its original state
A.clear();
for (int i = 0; i < N; i++) {
A.add(0);
}
// Condition 2: Append all positive elements of B[]
// to back of A[] and negative to front of A[]
while (!B.isEmpty()) {
int back = B.get(B.size() - 1);
B.remove(B.size() - 1);
if (back >= 0) {
A.add(back);
}
else {
A.add(0, back);
}
maxSum = Math.max(maxSum, maxSubArraySum(A));
}
return Math.max(maxSum, maxSumA);
}
public static void main(String[] args)
{
int N = 4;
// I have used List here .You can use an Array of
// your choice.
List<Integer> A = new ArrayList<>(
Arrays.asList(72, 23, -56, 80));
int M = 2;
List<Integer> B
= new ArrayList<>(Arrays.asList(50, 10));
System.out.println(
maxSubarraySum(N, A, M, B)); // Output: 179
}
}
Python3
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
def max_subarray_sum_with_operations(N, A, M, B):
max_sum = float('-inf')
# Calculate max subarray sum of A
max_sum_A = max_subarray_sum(A)
# Condition 1: Append all positive elements of B[] to front of A[] and negative to back of A[]
while B:
front = B.pop(0)
if front >= 0:
A.insert(0, front)
else:
A.append(front)
max_sum = max(max_sum, max_subarray_sum(A))
# Reset A to its original state
A = [0] * N
# Condition 2: Append all positive elements of B[] to back of A[] and negative to front of A[]
while B:
back = B.pop()
if back >= 0:
A.append(back)
else:
A.insert(0, back)
max_sum = max(max_sum, max_subarray_sum(A))
return max(max_sum, max_sum_A)
N = 4
A = [72, 23, -56, 80]
M = 2
B = [50, 10]
print(max_subarray_sum_with_operations(N, A, M, B)) # Output: 179
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static int SubArraySum(List<int> arr)
{
int maxSum = int.MinValue;
int currentSum = 0;
foreach(int num in arr)
{
currentSum = Math.Max(num, currentSum + num);
maxSum = Math.Max(maxSum, currentSum);
}
return maxSum;
}
static int maxSubarraySum(int N, List<int> A, int M,
List<int> B)
{
int maxSum = int.MinValue;
// Calculate max subarray sum of A
int maxSumA = SubArraySum(A);
// Condition 1: Append all positive elements of B[]
// to front of A[] and negative to back of A[]
while (B.Any()) {
int front = B.First();
B.RemoveAt(0);
if (front >= 0) {
A.Insert(0, front);
}
else {
A.Add(front);
}
maxSum = Math.Max(maxSum, SubArraySum(A));
}
// Reset A to its original state
A.Clear();
A.AddRange(Enumerable.Repeat(0, N));
// Condition 2: Append all positive elements of B[]
// to back of A[] and negative to front of A[]
while (B.Any()) {
int back = B.Last();
B.RemoveAt(B.Count - 1);
if (back >= 0) {
A.Add(back);
}
else {
A.Insert(0, back);
}
maxSum = Math.Max(maxSum, SubArraySum(A));
}
return Math.Max(maxSum, maxSumA);
}
static void Main(string[] args)
{
int N = 4;
List<int> A = new List<int>{ 72, 23, -56, 80 };
int M = 2;
List<int> B = new List<int>{ 50, 10 };
Console.WriteLine(
maxSubarraySum(N, A, M, B)); // Output: 179
}
}
JavaScript
function subArraySum(arr) {
let maxSum = -Infinity;
let currSum = 0;
for (let num of arr) {
currSum = Math.max(num, currSum + num);
maxSum = Math.max(maxSum, currSum);
}
return maxSum;
}
function maxSubarraySum(N, A, M, B) {
let maxsum = -Infinity;
// Calculate max subarray sum of A
let maxsum_A = subArraySum(A);
// Condition 1: Append all positive elements of B[] to front of A[] and negative to back of A[]
while (B.length > 0) {
let front = B.shift();
if (front >= 0) {
A.unshift(front);
} else {
A.push(front);
}
maxsum = Math.max(maxsum, subArraySum(A));
}
// Reset A to its original state
A = new Array(N).fill(0);
// Condition 2: Append all positive elements of B[] to back of A[] and negative to front of A[]
while (B.length > 0) {
let back = B.pop();
if (back >= 0) {
A.push(back);
} else {
A.unshift(back);
}
maxsum = Math.max(maxsum, subArraySum(A));
}
return Math.max(maxsum, maxsum_A);
}
let N = 4;
let A = [72, 23, -56, 80];
let M = 2;
let B = [50, 10];
console.log(maxSubarraySum(N, A, M, B)); // Output: 179
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem