A Sum Array Puzzle | JavaScript implementation of above approach ; Allocate memory for temporary arrays leftSum [ ] , rightSum [ ] and Sum [ ] ; Left most element of left array is always 0 ; Right most element of right array is always 0 ; Construct the left array ; Construct the right array ; Construct the sum array using left [ ] and right [ ] ; print the sum array ; Driver Code
function sumArray ( arr , n ) { let leftSum = new Array ( n ) ; let rightSum = new Array ( n ) ; let Sum = new Array ( n ) ; let i = 0 , j = 0 ; leftSum [ 0 ] = 0 ; rightSum [ n - 1 ] = 0 ; for ( i = 1 ; i < n ; i ++ ) leftSum [ i ] = arr [ i - 1 ] + leftSum [ i - 1 ] ; for ( j = n - 2 ; j >= 0 ; j -- ) rightSum [ j ] = arr [ j + 1 ] + rightSum [ j + 1 ] ; for ( i = 0 ; i < n ; i ++ ) Sum [ i ] = leftSum [ i ] + rightSum [ i ] ; for ( i = 0 ; i < n ; i ++ ) document . write ( Sum [ i ] + " " ) ; } let arr = [ 3 , 6 , 4 , 8 , 9 ] ; let n = arr . length ; sumArray ( arr , n ) ;