Maximum Subarray sum of A[] by adding any element of B[] at any end
Last Updated :
17 Apr, 2024
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
Maximize the sum of Array by formed by adding pair of elements
Given an array a[] of 2*N integers, The task is to make the array a[] of size N i.e, reducing it to half size such that, a[i] = ?(a[j] + a[k]) / N?, 0 < j, k < 2*N - 1. and form the array so that the sum of all the elements of the array a[], will be maximum. Output the maximum sum. Examples: I
6 min read
Maximize sum of an Array by flipping sign of all elements of a single subarray
Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once. Examples: Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the arr
9 min read
Maximum difference between sum of even and odd indexed elements of a Subarray
Given an array nums[] of size N, the task is to find the maximum difference between the sum of even and odd indexed elements of a subarray. Examples: Input: nums[] = {1, 2, 3, 4, -5}Output: 9Explanation: If we select the subarray {4, -5} the sum of even indexed elements is 4 and odd indexed element
8 min read
Maximum Subarray Sum possible by replacing an Array element by its Square
Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square. Examples: Input: a[] = {1, -5, 8, 12, -8} Output: 152 Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possib
12 min read
Maximum Subarray Sum Excluding Certain Elements
Given an array of A of n integers and an array B of m integers find the Maximum Contiguous Subarray Sum of array A such that any element of array B is not present in that subarray. Examples : Input : A = {1, 7, -10, 6, 2}, B = {5, 6, 7, 1} Output : 2 Explanation Since the Maximum Sum Subarray of A i
15+ min read
Sum of maximum of all subarrays | Divide and Conquer
Given an array arr[] of length N, the task is to find the sum of the maximum elements of every possible sub-array of the array.Examples: Input : arr[] = {1, 3, 1, 7} Output : 42 Max of all sub-arrays: {1} - 1 {1, 3} - 3 {1, 3, 1} - 3 {1, 3, 1, 7} - 7 {3} - 3 {3, 1} - 3 {3, 1, 7} - 7 {1} - 1 {1, 7} -
12 min read
Maximum subarray sum possible after removing at most K array elements
Given an array arr[] of size N and an integer K, the task is to find the maximum subarray sum by removing at most K elements from the array. Examples: Input: arr[] = { -2, 1, 3, -2, 4, -7, 20 }, K = 1 Output: 26 Explanation: Removing arr[5] from the array modifies arr[] to { -2, 1, 3, -2, 4, 20 } Su
15+ min read
Maximize subarray sum by inverting sign of elements of any subarray at most twice
Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negativ
10 min read
Maximize Array sum by adding multiple of another Array element in given ranges
Given two arrays X[] and Y[] of length N along with Q queries each of type [L, R] that denotes the subarray of X[] from L to R. The task is to find the maximum sum that can be obtained by applying the following operation for each query: Choose an element from Y[]. Add multiples with alternate +ve an
15+ min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
11 min read