Maximum Erasure Value in C++

C++Server Side ProgrammingProgramming

Given an array of positive integers, the task is to erase a subarray containing all the unique elements. What you get by erasing the subarray is equal to the sum of its elements.

Return the maximum sum of the current subarray by erasing the terms before or after it, we can get the maximum sum by erasing exactly one subarray.

An array arr is called to be a subarray of a if it forms a contiguous subsequence of a that is if it is equal to a[l], a[l+1],..., a[r] for some (l,r). For example,

Input-1

arr[ ] = { 1,2,4,5,6 }

Output

17

Explanation − The optimal subarray is {2,4,5,6}.

Input-2

arr[ ]= {5,3,1,3,5,3,1,3,5}

Output

9

Explanation − The optimal subarray is {5,3,1} or {1,3,5}.

Approach to solve this problem

To solve this problem, we will use the concept of a Sliding Window. This technique shows how a nested loop can be converted into a single loop to reduce the time complexity.

In this technique, we will first initialize two pointers for (left and right) and the size of the window as ‘win’. While iterating through the array we will check whether the size of a particular win is maximum or not. If we find it maximum, we will return it as output.

The approach to solving this problem,

  • Take input an array of positive integers.

  • An integer function maximumUniqueSubarray(vector&arr) takes an array as input.

  • Taking three-pointers ‘I’, ‘j’ and window size ‘win’ and iterating over the array and finding if the current window having an element is present in the HashSet then move the window and again check for another element. If it is not present, then insert it into the HashSet and decrement the window size which removes the previous element.

  • Find the maximum in the result and the window value.

  • Return the result.

Example

#include<bits/stdc++.h>
using namespace std;
int maximumUniqueSubarray(vector<int>& arr) {
   int result = 0;
   unordered_set<int> hashset;
   for (int i = 0, j = 0, win = 0; j < arr.size(); j++) {
      while (hashset.find(arr[j]) != hashset.end()) {
         hashset.erase(arr[i]);
         win -= arr[i];
         i++;
      }
      hashset.insert(arr[j]);
      win += arr[j];
      result = max(result, win);
   }
   return result;
}
int main(){
   vector<int>nums;
   nums<<5,3,1,3,5,3,1,3,5;
   cout<<maximumUniqueSubarray(nums)<<endl;
   return 0;
}

Output

Running the above code will generate the output as,

9
raja
Published on 04-Feb-2021 16:31:30
Advertisements