Find Sum of all unique sub | 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 ; Drivers code
def findSubarraySum ( arr , n ) : NEW_LINE INDENT cArray = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT cArray [ i + 1 ] = cArray [ i ] + arr [ i ] NEW_LINE DEDENT subArrSum = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , 1 ) : NEW_LINE INDENT subArrSum . append ( cArray [ j ] - cArray [ i - 1 ] ) NEW_LINE DEDENT DEDENT subArrSum . sort ( reverse = False ) NEW_LINE totalSum = 0 NEW_LINE for i in range ( 0 , len ( subArrSum ) - 1 , 1 ) : NEW_LINE INDENT if ( subArrSum [ i ] == subArrSum [ i + 1 ] ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( subArrSum [ j ] == subArrSum [ i ] and j < len ( subArrSum ) ) : NEW_LINE INDENT subArrSum [ j ] = 0 NEW_LINE j += 1 NEW_LINE DEDENT subArrSum [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( subArrSum ) , 1 ) : NEW_LINE INDENT totalSum += subArrSum [ i ] NEW_LINE DEDENT return totalSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 3 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSubarraySum ( arr , n ) ) NEW_LINE DEDENT