Maximum Sub Square Sum

 Coding Problem Keys 

 Maximum Sub Square Sum 

 Problem Statement 

Given a square matrix of size N x N where each cell is filled with a number between -9 and 9. A sub square of size k is any set of k contiguous columns and k contiguous rows. For any sub square, the sum of elements in its cells is called a sub square sum. Given the N x N square, write a program to find the maximum sub square sum. Note that a 1 x 1 square (k = 1) is not considered a sub square.

 Boundary Condition(s) 

2 <= N <= 1000

 Input Format 

The first line contains the value of N.
The next N lines contain N integers each separated by space(s).

 Output Format 

The first line contains the maximum sub square sum.

 Example Input/Output 1 

 Input 

4
2 -8 4 -6
7 1 -5 3
-9 7 6 5
8 3 2 -4

 Output 

20

 Explanation 

The 2 by 2 square sums are
2 -8 -4
6 9 9
9 18 9

The 3 by 3 square sums are
5 7
20 18

And the 4 by 4 square sum is 16. Hence the maximum sub square sum is 20.

 Example Input/Output 2 

 Input 

3
1 1 0
1 2 2
3 0 4

 Output 

14

 Explanation 

As all the entries are non-negative, the 3 by 3 sub square (which has a sum of 14) is the maximum.

 Max Execution Time Limit: 5000 millisecs 

 Solution 

 Programming Language: C Language 

#include <stdio.h>
#include <stdlib.h>
int maxsubsum(int n, int mat[n][n], int k){
    int stripsum[n][n];
    int i,j;
    for(j=0;j<n;j++){
        int sum=0;
        for(i=0;i<k;i++)
            sum+=mat[i][j];
        stripsum[0][j]=sum;
        for(i=1;i<=n;i++){
            sum+=mat[i+k-1][j]-mat[i-1][j];
            stripsum[i][j]=sum;
        }
    }
    int max=-99999;
    for(i=0;i<=n-k;i++){
        int sum=0;
        for(j=0;j<k;j++){
            sum+=stripsum[i][j];
        }
        if(sum>max)
            max=sum;
        for(j=1;j<=n-k;j++){
            sum+=stripsum[i][j+k-1]-stripsum[i][j-1];
            if(sum>max)
                max=sum;
        }
    }
    return max;
}
int main() {
    int n,i,k,j;
    scanf("%d",&n);
    int mat[n][n];
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            scanf("%d",&mat[i][j]);
        }
    }
    int max=-99999;
    for(k=2;k<=n;k++){
        int sum=maxsubsum(n,mat,k);
        if(sum>max){
            max=sum;
        }
    }
    printf("%d",max);
}

// Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Turning Book Pages

Jooney's Amusement Park

Shift Largest Digit - Sum

Reverse Column - First and Last

String With Most Vowels

Multiply Three Numbers