A Sum Array Puzzle | C ++ implementation of above approach ; Allocate memory for temporary arrays leftSum [ ] , rightSum [ ] and Sum [ ] ; Left most element of left array is always 0 ; Rightmost 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 constructed prod array ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumArray ( int arr [ ] , int n ) { int leftSum [ n ] , rightSum [ n ] , Sum [ n ] , i , j ; 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 ++ ) cout << Sum [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 3 , 6 , 4 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumArray ( arr , n ) ; return 0 ; }