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 ; 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
using System ; using System . Collections . Generic ; class GFG { public static int maxSumSubarray ( int [ ] arr ) { int i = 0 , j = 1 ; HashSet < int > set = new HashSet < int > ( ) ; set . Add ( arr [ 0 ] ) ; int sum = arr [ 0 ] ; int maxsum = sum ; while ( i < arr . Length - 1 && j < arr . Length ) { if ( ! set . Contains ( arr [ j ] ) ) { sum = sum + arr [ j ] ; maxsum = Math . Max ( sum , maxsum ) ; set . Add ( arr [ j ++ ] ) ; } else { sum -= arr [ i ] ; set . Remove ( arr [ i ++ ] ) ; } } return maxsum ; } public static void Main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 1 , 5 } ; int ans = maxSumSubarray ( arr ) ; Console . WriteLine ( ans ) ; } }