VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-subarray-sum-with-same-first-and-last-element-formed-by-removing-elements/

⇱ Maximum subarray sum with same first and last element formed by removing elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum subarray sum with same first and last element formed by removing elements

Last Updated : 23 Jul, 2025

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:


Output: 
2

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment