I'm trying to solve this Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded. Can someone help me improve its performance in order to pass the time limit, please?
Problem
You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.
Input
First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).
Output
print a single integer denoting the answer.
Time Limit:
1.5 sec(s) for each input file.
Result Time:
Input 1: 1.999309
Input 2: 1.998019
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n = 0, q = 0;
cin >> n >> q;
vector<int> nums(n);
for (size_t i = 0; i < n; i++)
{
cin >> nums[i];
}
for (size_t i = 0; i < q; i++)
{
float ans = 0.0f;
int leftIndex = 0, rightIndex = 0;
cin >> leftIndex >> rightIndex;
leftIndex = leftIndex - 1;
rightIndex = rightIndex - 1;
for (size_t i = leftIndex; i <= rightIndex; i++)
{
ans = ans + nums[i];
}
ans = ans / (rightIndex - leftIndex) + 1;
cout << floor(ans) << "\n";
}
system("pause");
}