![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
2
Time Complexity: O(N)
Auxiliary Space: O(N)