Home > Back-end >  Can we use std::max in cpp for finding maximum element in a subbarray?
Can we use std::max in cpp for finding maximum element in a subbarray?

Time:12-24

For ex- if we have an array A ={1, 2 , 3, 4, 5} and I want to find max element between A[i] and A[i k]. Can I use max function for that , I tried to use it but I can't. Please tell me if they any other way to do it.

I need to do this

vector <int> max_of_subarrays(int *arr, int n, int k)
    {
        // your code here
        vector<int> v;
        for(int i=0; i<n 1-k; i  ){
            int result = arr[i];
            v.push_back(max(result,arr k)); 
        }
        return v;

CodePudding user response:

You can use std:max_element. It takes two iterators and returns an iterator to the maximum element in the specified range. You can use pointers to array elements so you can do something like:

vector <int> max_of_subarrays(int *arr, int n, int k) {
    vector<int> v;
    for(int i=0; i<n 1-k; i  ) {
        v.push_back(*max_element(arr   i , arr   k)); 
    }
    return v;
}
  • Related