Php Program for Mean of range in array
Last Updated :
13 Jan, 2022
Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line.
Examples :Â
Input : arr[] = {1, 2, 3, 4, 5}
q = 3
0 2
1 3
0 4
Output : 2
3
3
Here for 0 to 2 (1 + 2 + 3) / 3 = 2
Input : arr[] = {6, 7, 8, 10}
q = 2
0 3
1 2
Output : 7
7
Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query. Â
PHP
<?php
function findMean( $arr , $l , $r )
{
$sum = 0;
$count = 0;
for ( $i = $l ; $i <= $r ; $i ++)
{
$sum += $arr [ $i ];
$count ++;
}
$mean = floor ( $sum / $count );
return $mean ;
}
$arr = array (1, 2, 3, 4, 5);
echo findMean( $arr , 0, 2), "
";
echo findMean( $arr , 1, 3), "
";
echo findMean( $arr , 0, 4), "
";
?>
|
Output :Â
2
3
3
Time Complexity: O(n)
Please refer complete article on Mean of range in array for more details!
Share your thoughts in the comments
Please Login to comment...