Sum of all odd length subarrays | Function that finds the sum of all the element of subarrays of odd length ; Stores the sum ; Size of array ; Traverse the given array arr [ ] ; Add to the sum for each contribution of the arr [ i ] ; Return the final sum ; Given array arr [ ] ; Function call
function OddLengthSum ( arr ) { let sum = 0 ; let l = arr . length ; for ( let i = 0 ; i < l ; i ++ ) { sum += Math . floor ( ( ( i + 1 ) * ( l - i ) + 1 ) / 2 ) * arr [ i ] ; } return sum ; } let arr = [ 1 , 5 , 3 , 1 , 2 ] ; document . write ( OddLengthSum ( arr ) ) ;