Largest Sum Contiguous Subarray having unique elements | C ++ program for the above approach ; Function to calculate required maximum subarray sum ; Initialize two pointers ; Stores the unique elements ; Insert the first element ; Current max sum ; Global maximum sum ; Update sum & increment j auto pos = s . find ( 3 ) ; ; Add the current element ; Update sum and increment i and remove arr [ i ] from set ; Remove the element from start position ; Return the maximum sum ; Driver Code ; Given array arr [ ] ; Function Call ; Print the maximum sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumSubarray ( int arr [ ] , int n ) { int i = 0 , j = 1 ; set < int > set ; set . insert ( arr [ 0 ] ) ; int sum = arr [ 0 ] ; int maxsum = sum ; while ( i < n - 1 && j < n ) { const bool is_in = set . find ( arr [ j ] ) != set . end ( ) ; if ( ! is_in ) { sum = sum + arr [ j ] ; maxsum = max ( sum , maxsum ) ; set . insert ( arr [ j ++ ] ) ; } else { sum -= arr [ i ] ; set . erase ( arr [ i ++ ] ) ; } } return maxsum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 5 } ; int ans = maxSumSubarray ( arr , 5 ) ; cout << ( ans ) ; }