If N is an odd number, the main diagonal and the secondary diagonal have an element in common (namely, the (N/2, N/2)-th element of the matrix, in 0-based indexing). And if N is even, they don't have any element in common. Therefore, there will be two cases:

  • N is odd: Note that regardless of what value we put in the position that is shared by the two diagonal will not have any impact on the total outcome since it will cancel itself out. Therefore, the answer will be:

    (summation of N-1 largest elements) - (summation of N-1 smallest elements)

  • N is even: In this case, the two diagonal doesn't have any element in common. So, the answer will be:

    (summation of N largest elements) - (summation of N smallest elements)

We will need to sort all the elements in the matrix to find the answer. You can see the implementation below for details.

C++ code:

#include <bits/stdc++.h>

using namespace std;


int main()
{
    int n,x,m,ans = 0;
    std::vector<int> v;

    scanf("%d",&n);

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++) 
        { 
            scanf("%d",&x); 
            v.push_back(x); 
        }
    }
    
    sort(v.begin(), v.end());

    m = n*n; 

    if(n & 1) //when n is odd
    {
        for(int i = 0; i < n-1; i++) ans -= v[i];
        for(int i = m-1; i >= m-n+1; i--) ans += v[i];
    }

    else //when n is even
    {
        for(int i = 0; i < n; i++) ans -= v[i];
        for(int i = m-1; i >= m-n; i--) ans += v[i];
    }

    cout << ans << endl;
    

    return 0;
}

Statistics

89% Solution Ratio
ghazanfarEarliest, Dec '16
mdshadeshFastest, 0.0s
madhabLightest, 5.5 kB
Nusab19Shortest, 77B
Toph uses cookies. By continuing you agree to our Cookie Policy.