Mean of range in array | Javascript program to find floor value of mean in range l to r ; To calculate prefixSum of array ; Calculate prefix sum of array ; To return floor of mean in range l to r ; Sum of elements in range l to r is prefixSum [ r ] - prefixSum [ l - 1 ] Number of elements in range l to r is r - l + 1 ; Driver code
let MAX = 1000005 ; let prefixSum = new Array ( MAX ) ; prefixSum . fill ( 0 ) ; function calculatePrefixSum ( arr , n ) { prefixSum [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] ; } function findMean ( l , r ) { if ( l == 0 ) return parseInt ( Math . floor ( prefixSum [ r ] / ( r + 1 ) ) , 10 ) ; return parseInt ( Math . floor ( ( prefixSum [ r ] - prefixSum [ l - 1 ] ) / ( r - l + 1 ) ) , 10 ) ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let n = arr . length ; calculatePrefixSum ( arr , n ) ; document . write ( findMean ( 1 , 2 ) + " " ) ; document . write ( findMean ( 1 , 3 ) + " " ) ; document . write ( findMean ( 1 , 4 ) + " " ) ;