Mean of range in array | Java 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 program to test above functions
public class Main { public static final int MAX = 1000005 ; static int prefixSum [ ] = new int [ MAX ] ; static void calculatePrefixSum ( int arr [ ] , int n ) { prefixSum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] ; } static int findMean ( int l , int r ) { if ( l == 0 ) return ( int ) Math . floor ( prefixSum [ r ] / ( r + 1 ) ) ; return ( int ) Math . floor ( ( prefixSum [ r ] - prefixSum [ l - 1 ] ) / ( r - l + 1 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; calculatePrefixSum ( arr , n ) ; System . out . println ( findMean ( 1 , 2 ) ) ; System . out . println ( findMean ( 1 , 3 ) ) ; System . out . println ( findMean ( 1 , 4 ) ) ; } }