Maximum subarray sum with same first and last element formed by removing elements
Last Updated :
25 Nov, 2021
Given an array arr[] of N integers, the task is to find the maximum sum of subarray having length an at least 2 whose first and last elements are the same after removing any number of array elements. If there exists no such array, then print 0.
Examples:
Input: arr[] = {-1, -3, -2, 4, -1, 3}
Output: 2
Explanation: Choose the sub-array { -1, -3, -2, 4, -1} and remove the elements -3 and -2 which makes the sub-array as { -1, 4, -1} with sum equal to 2 which is the maximum.
Input: arr[] = {-1}
Output: 0
Approach: The given problem can be solved by using the idea is that first find all the subarrays having the first and the last element same and removing all the negative elements between those first and the last element. This idea can be implemented by the idea discussed in this article using an unordered map. Follow the steps below to solve the given problem:
- Initialize a variable, say res as INT_MIN that stores the resultant maximum sum of the subarray.
- Initialize a variable, say currentSum as 0 that stores the running prefix sum of the array.
- Initialize a unordered_map, say memo[] that stores the value of each array element mapped with its prefix sum.
- Iterate over the range [0, N) using the variable i and perform the following tasks:
- Add the value of the current array element arr[i] to the variable currentSum.
- If arr[i] is present in the map, and If the value of arr[i] is positive then update the value of res to the maximum of res and (currentSum - M[arr[i]] + arr[i]). Otherwise, update the value of res to the maximum of res and (currentSum - M[arr[i]] + 2*arr[i]).
- Otherwise, Insert the value arr[i] mapped with currentSum.
- If the current value arr[i] is negative, then decrement it from currentSum to exclude the negative element for the possible subarray.
- After completing the above steps, print the value of res as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum sum
// of sub-array
int maximumSubarraySum(vector<int>& arr)
{
// Initialize the variables
int N = arr.size();
unordered_map<int, int> memo;
int res = INT_MIN;
int currsum = 0, currval = 0;
// Traverse over the range
for (int i = 0; i < N; ++i) {
// Add the current value to the
// variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;
// Calculate the result
if (memo.count(currval) != 0) {
if (currval > 0)
res = max(
res,
currsum - memo[currval]
+ currval);
else
res = max(
res,
currsum - memo[currval]
+ 2 * currval);
}
else
memo[currval] = currsum;
if (currval < 0)
currsum = currsum - currval;
}
// Return the answer
return res;
}
// Driver Code
int main()
{
vector<int> arr = { -1, -3, 4, 0, -1, -2 };
cout << maximumSubarraySum(arr);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to find the maximum sum
// of sub-array
static int maximumSubarraySum(int arr[], int N)
{
// Initialize the variables
HashMap<Integer, Integer> memo = new HashMap<>();
int res = Integer.MIN_VALUE;
int currsum = 0, currval = 0;
// Traverse over the range
for (int i = 0; i < N; ++i) {
// Add the current value to the
// variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;
// Calculate the result
if (memo.containsKey(currval)) {
if (currval > 0)
res = Math.max(
res, currsum - memo.get(currval)
+ currval);
else
res = Math.max(
res, currsum - memo.get(currval)
+ 2 * currval);
}
else
memo.put(currval, currsum);
if (currval < 0)
currsum = currsum - currval;
}
// Return the answer
return res;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { -1, -3, 4, 0, -1, -2 };
int N = 6;
System.out.println(maximumSubarraySum(arr, N));
}
}
// This code is contributed by dwivediyash
Python3
# Python3 program for the above approach
import sys
# Function to find the maximum sum
# of sub-array
def maximumSubarraySum(arr) :
# Initialize the variables
N = len(arr);
memo = {};
res = -(sys.maxsize - 1);
currsum = 0;
currval = 0;
# Traverse over the range
for i in range(N) :
# Add the current value to the
# variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;
# Calculate the result
if currval in memo :
if (currval > 0) :
res = max(res,currsum - memo[currval] + currval);
else :
res = max(res,currsum - memo[currval] + 2 * currval);
else :
memo[currval] = currsum;
if (currval < 0) :
currsum = currsum - currval;
# Return the answer
return res;
# Driver Code
if __name__ == "__main__" :
arr = [ -1, -3, 4, 0, -1, -2 ];
print(maximumSubarraySum(arr));
# This code is contributed by AnkThon
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the maximum sum
// of sub-array
static int maximumSubarraySum(int[] arr, int N)
{
// Initialize the variables
Dictionary<int, int> memo = new
Dictionary<int, int>();
int res = Int32.MinValue;
int currsum = 0, currval = 0;
// Traverse over the range
for (int i = 0; i < N; ++i) {
// Add the current value to the
// variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;
// Calculate the result
if (memo.ContainsKey(currval)) {
if (currval > 0)
res = Math.Max(
res, currsum - memo[(currval)]
+ currval);
else
res = Math.Max(
res, currsum - memo[(currval)]
+ 2 * currval);
}
else
memo.Add(currval, currsum);
if (currval < 0)
currsum = currsum - currval;
}
// Return the answer
return res;
}
// Driver Code
public static void Main()
{
int[] arr = { -1, -3, 4, 0, -1, -2 };
int N = 6;
Console.WriteLine(maximumSubarraySum(arr, N));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to find the maximum sum
// of sub-array
function maximumSubarraySum(arr) {
// Initialize the variables
let N = arr.length;
let memo = new Map();
let res = -99999999;
let currsum = 0, currval = 0;
// Traverse over the range
for (let i = 0; i < N; ++i) {
// Add the current value to the
// variable currsum for prefix sum
currval = arr[i];
currsum = currsum + currval;
// Calculate the result
if (memo.has(currval)) {
if (currval > 0)
res = Math.max(
res,
currsum - memo.get(currval)
+ currval);
else
res = Math.max(
res,
currsum - memo.get(currval)
+ 2 * currval);
}
else
memo.set(currval, currsum);
if (currval < 0)
currsum = currsum - currval;
}
// Return the answer
return res;
}
// Driver Code
let arr = [-1, -3, 4, 0, -1, -2];
document.write(maximumSubarraySum(arr));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum sum of Array formed by replacing each element with sum of adjacent elements Given an array arr[] of size N, the task is to find the maximum sum of the Array formed by replacing each element of the original array with the sum of adjacent elements.Examples: Input: arr = [4, 2, 1, 3] Output: 23 Explanation: Replacing each element of the original array with the sum of adjacent
9 min read
Maximize the maximum subarray sum after removing atmost one element Given an array arr[] of N integers, the task is to find the maximum sum of a subarray with at most one deletion allowed. The size of subarray to be considered should be at least 1.Examples: Input: arr[] = {1, 2, 3, -2, 3} Output: 9 The maximum sub-array sum is given by the sub-array {2, 3, -2, 3} He
2 min read
Subarray with largest sum after excluding its maximum element Given an array arr[], the task is to find the starting and ending indices of the subarray with the largest sum after excluding its maximum element.Examples: Input: arr[] = {5, -2, 10, -1, 4} Output: 1 5 Explanation: Subarray[1:5] = {5, -2, 10, -1, 4} Sum of subarray excluding maximum element = 5 + (
9 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
Maximize Array sum by replacing middle elements with min of Subarray corners Given an array A[] of length N. Then your task is to output the maximum sum that can be achieved by using the given operation at any number of times (possibly zero): Select a subarray, whose length is at least 3.Replace all the middle elements (Except the first and last) with a minimum of elements a
7 min read