Open In App

Maximum Subarray sum of A[] by adding any element of B[] at any end

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Output
179

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

Output
179

Time Complexity: O(N)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads