Mean of range in array | Python3 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
import math as mt NEW_LINE MAX = 1000005 NEW_LINE prefixSum = [ 0 for i in range ( MAX ) ] NEW_LINE def calculatePrefixSum ( arr , n ) : NEW_LINE INDENT prefixSum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT DEDENT def findMean ( l , r ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return mt . floor ( prefixSum [ r ] / ( r + 1 ) ) NEW_LINE DEDENT return ( mt . floor ( ( prefixSum [ r ] - prefixSum [ l - 1 ] ) / ( r - l + 1 ) ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE calculatePrefixSum ( arr , n ) NEW_LINE print ( findMean ( 0 , 2 ) ) NEW_LINE print ( findMean ( 1 , 3 ) ) NEW_LINE print ( findMean ( 0 , 4 ) ) NEW_LINE