Find Sum of all unique sub | Java for finding sum of all unique subarray sum ; function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those sums that appear once . ; Driver code
import java . util . * ; class GFG { static int findSubarraySum ( int [ ] arr , int n ) { int res = 0 ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( m . containsKey ( sum ) ) { m . put ( sum , m . get ( sum ) + 1 ) ; } else { m . put ( sum , 1 ) ; } } } for ( Map . Entry < Integer , Integer > x : m . entrySet ( ) ) if ( x . getValue ( ) == 1 ) res += x . getKey ( ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = arr . length ; System . out . println ( findSubarraySum ( arr , n ) ) ; } }