Largest Sum Contiguous Subarray having unique elements | 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 ; Given array arr [ ] ; Function Call ; Print the maximum sum
function maxSumSubarray ( arr , n ) { var i = 0 , j = 1 ; var set = new Set ( ) ; set . add ( arr [ 0 ] ) ; var sum = arr [ 0 ] ; var maxsum = sum ; while ( i < n - 1 && j < n ) { var is_in = set . has ( arr [ j ] ) ; if ( ! is_in ) { sum = sum + arr [ j ] ; maxsum = Math . max ( sum , maxsum ) ; set . add ( arr [ j ++ ] ) ; } else { sum -= arr [ i ] ; set . delete ( arr [ i ++ ] ) ; } } return maxsum ; } var arr = [ 1 , 2 , 3 , 1 , 5 ] ; var ans = maxSumSubarray ( arr , 5 ) ; document . write ( ans ) ;