Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we use std::max in cpp for finding maximum element in a subbarray?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading