Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; Function for finding grandSum ; Calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; Store all subarray sum in vector ; Sort the vector ; Mark all duplicate sub - array sum to zero ; Calculate total sum ; Return totalSum ; Driver Code
import java . util . * ; class GFG { static int findSubarraySum ( int arr [ ] , int n ) { int i , j ; int cArray [ ] = new int [ n + 1 ] ; for ( i = 0 ; i < n ; i ++ ) cArray [ i + 1 ] = cArray [ i ] + arr [ i ] ; Vector < Integer > subArrSum = new Vector < Integer > ( ) ; for ( i = 1 ; i <= n ; i ++ ) for ( j = i ; j <= n ; j ++ ) subArrSum . add ( cArray [ j ] - cArray [ i - 1 ] ) ; Collections . sort ( subArrSum ) ; int totalSum = 0 ; for ( i = 0 ; i < subArrSum . size ( ) - 1 ; i ++ ) { if ( subArrSum . get ( i ) == subArrSum . get ( i + 1 ) ) { j = i + 1 ; while ( subArrSum . get ( j ) == subArrSum . get ( i ) && j < subArrSum . size ( ) ) { subArrSum . set ( j , 0 ) ; j ++ ; } subArrSum . set ( i , 0 ) ; } } for ( i = 0 ; i < subArrSum . size ( ) ; i ++ ) totalSum += subArrSum . get ( i ) ; return totalSum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . print ( findSubarraySum ( arr , n ) ) ; } }