![]() |
VOOZH | about |
You are given an array arr[] consisting of n positive integers and a set of q queries represented by a 2D array queries queries[][]. Each query contains two integers l and r, indicating a range of indices in the array.
For every query, calculate the mean of the elements in the subarray from index l to index r (inclusive). After computing the mean, return its floor value.
Examples:
Input: arr[] = [3, 7, 2, 8, 2] , queries[][] = [[0,1], [1, 3], [2, 4]]
Output: 5 5 4
Explanation:
For query [0, 1] - Elements in the range are [3, 7], Mean is (3+7)/2 = 5, Floor value is 5.
For query [1, 3] - Elements in the range are [7, 2, 8], Mean is (7+2+8)/3 = 5.6, Floor value is 5.
For query [2, 4] - Elements in the range are [2, 8, 2], Mean is (2+8+2)/3 = 4, Floor value is 4.Input: arr[] = [10, 20, 30, 40, 50, 60], queries[][] = [[3, 5]]
Output: 50
Explanation: For query [3, 5] - Elements in the range are [40, 50, 60], Mean is (40+50+60)/3 = 50, Floor value is 50.
The idea is to process each query separately by iterating over the given range l to r and computing the sum and count of elements. Since the mean is sum/count, we can directly compute its floor value using integer division. The approach ensures that each query is handled independently.
Dry run for arr[] = [3, 7, 2, 8, 2] , queries[][] = [[0,1], [1, 3], [2, 4]]:
Final answer: 5 5 4
5 5 4
Time Complexity: O(n * q), for each of the q queries, we iterate over the range l to r, taking O(n) time.
Auxiliary Space: O(1)
Use a prefix sum array to calculate the sum from l to r in O(1) time. For each query, compute the range sum using the prefix array and divide it by the number of elements to obtain the mean.
Dry run for arr[] = [3, 7, 2, 8, 2] , queries[][] = [[0,1], [1, 3], [2, 4]]:
Final answer: 5 5 4
5 5 4
Time Complexity: O(n + q), as the method efficiently computes prefix sum in O(n) and processes each query in O(1).
Auxiliary Space: O(n)