Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIPhp Program for Mean of range in array

Php Program for Mean of range in array

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
// PHP program to find floor 
// value of mean in range l to r
  
// To find mean of 
// range in l to r
function findMean($arr, $l, $r)
{
    // Both sum and count 
    // are initialize to 0
    $sum = 0;
    $count = 0;
  
    // To calculate sum and 
    // number of elements in
    // range l to r
    for ($i = $l; $i <= $r; $i++) 
    {
        $sum += $arr[$i];
        $count++;
    }
  
    // Calculate floor 
    // value of mean
    $mean = floor($sum / $count);
  
    // Returns mean of array
    // in range l to r
    return $mean;
}
  
// Driver Code
$arr = array(1, 2, 3, 4, 5);
echo findMean($arr, 0, 2), "
";
echo findMean($arr, 1, 3), "
";
echo findMean($arr, 0, 4), "
";
  
// This code is contributed by ajit
?>


Output : 

2
3
3

Time Complexity: O(n)

Please refer complete article on Mean of range in array for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
13 Jan, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments