c find the sum of elements between the minimum and the maximum element in the matrix

As my comment stated, one solution is to realize that the two-dimensional array has a layout of its data in contiguous memory. Thus getting the minimum, maximum, and sum become simple, since you would traverse the two-dimensional array in the same way as a one-dimensional array.

Here is a solution using C++ algorithm functions.

#include <algorithm>
#include <iostream>
#include <numeric>

int main()
{
    int a[5][5] = {
        {0,4,6,3,5},
        {7,1,5,6,2},
        {6,8,8,5,2},
        {4,1,5,2,2},
        {4,3,6,5,9} };

    // Get both the position of the minimum and maximum element in the array  
    auto pr = std::minmax_element(&a[0][0], &a[4][5]);

    // add up all elements between the min and max elements 
    int answer = std::accumulate(std::next(pr.first), pr.second, 0);

    // output results
    std::cout << answer;
}

Output:

100

Yes, that is the entire code.

So what was done?

First, we use std::minmax_element to traverse the array starting from a pointer to the first element (&a[0][0]) to one passed the last element (&a[4][5]). Note the arguments to the function — the reason why this works is that a two-dimensional array has that contiguous layout I mentioned earlier. So it’s just a matter of figuring out the starting and ending positions.

The return value of std::minmax_element is a std::pair<int*, int*> that point to the minimum element (the first) and maximum element (the second). That is what the pr denotes.

Once that’s done, we can quickly add up the items between the minimum and maximum elements by using std::accumulate with the pointers we have from pr.

Note that the first argument to std::accumulate is the next value after the minimum value found. That is the reason for the std::next in the first argument — it takes us to the next value.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top