I want to calculate the maximum number between two indexes in an array in an efficient way. I will be given a very large number of queries in each query I will be given indexes l and r where I need to find the maximum number between these two indexes
when I tried to solve that problem my solution had a time complexity of o((l-r)*q) where q is the number of queries
#include <bits/stdc++.h>
using namespace std;
int main()
{
int number = 1e6;
vector <int> v(number);
// the user should enter the elements of the vector
for(auto &i : v) cin >> i;
int number_of_queries=1e6;
for(int i=0; i < number_of_queries; ++i)
{
int left_index,right_index,max_number = -1;
//the user should enter the left and the right index (base zero)
cin >> left_index >> right_index;
//searching between the indexes for the maximum number between them
for(int j=left_index ; j <= right_index; ++j) max_number=max(max_number,v[j]);
//printing the number
cout << max_number << "\n";
}
}
That's what I came up with
I want to know if there is a way to decrease the time complexity by maybe doing some operations on the array before starting
note that the array contains only positive numbers and it can contain the same number more than one time
Thank you in advance