A Sum Array Puzzle | Java 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 function to test above function
import java . util . * ; import java . lang . * ; import java . io . * ; class Geeks { public static void sumArray ( int arr [ ] , int n ) { int leftSum [ ] = new int [ n ] ; int rightSum [ ] = new int [ n ] ; int Sum [ ] = new int [ n ] ; int 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 ++ ) System . out . print ( Sum [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 6 , 4 , 8 , 9 } ; int n = arr . length ; sumArray ( arr , n ) ; } }