Largest Sum Contiguous Subarray having unique elements | Java 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
import java . io . * ; import java . lang . Math ; import java . util . * ; public class GFG { public static int maxSumSubarray ( int [ ] arr ) { int i = 0 , j = 1 ; HashSet < Integer > set = new HashSet < Integer > ( ) ; 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 ) ; System . out . println ( ans ) ; } }