Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print maximum sum square sub-matrix of given size in C Program.
Given a matrix of NxN, find a sub-matrix of MxM where M<=N and M>=1 such that the sum of all elements in the MxM matrix is maximum. The input matrix can contain zero, positive and negative integer values.
Syntax
void findMaxSumSubMatrix(int matrix[][SIZE], int size, int k);
Algorithm
This solution uses a sliding window technique to optimize the time complexity from O(N²M²) to O(N²M) −
- First compute column-wise sums for each possible k-length window
- Then use sliding window on rows to find maximum sum sub-matrix
- Track the position of maximum sum and print the sub-matrix
Example
#include <stdio.h>
#include <limits.h>
#define SIZE 5
void findMaxSumSubMatrix(int arr[][SIZE], int k) {
if (k > SIZE) return;
int colSum[SIZE][SIZE];
/* Calculate column-wise sums for k-length windows */
for (int j = 0; j < SIZE; j++) {
int sum = 0;
for (int i = 0; i < k; i++)
sum += arr[i][j];
colSum[0][j] = sum;
for (int i = 1; i < SIZE - k + 1; i++) {
sum += (arr[i + k - 1][j] - arr[i - 1][j]);
colSum[i][j] = sum;
}
}
int maxSum = INT_MIN;
int maxRow = 0, maxCol = 0;
/* Find maximum sum using sliding window on rows */
for (int i = 0; i < SIZE - k + 1; i++) {
int sum = 0;
for (int j = 0; j < k; j++)
sum += colSum[i][j];
if (sum > maxSum) {
maxSum = sum;
maxRow = i;
maxCol = 0;
}
for (int j = 1; j < SIZE - k + 1; j++) {
sum += (colSum[i][j + k - 1] - colSum[i][j - 1]);
if (sum > maxSum) {
maxSum = sum;
maxRow = i;
maxCol = j;
}
}
}
/* Print the maximum sum sub-matrix */
printf("Maximum sum sub-matrix:
");
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++)
printf("%d ", arr[maxRow + i][maxCol + j]);
printf("
");
}
printf("Maximum sum: %d
", maxSum);
}
int main() {
int matrix[SIZE][SIZE] = {
{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5}
};
int k = 2;
printf("Input matrix:
");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++)
printf("%d ", matrix[i][j]);
printf("
");
}
printf("
");
findMaxSumSubMatrix(matrix, k);
return 0;
}
Input matrix: 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 Maximum sum sub-matrix: 4 4 5 5 Maximum sum: 18
Time Complexity
The optimized solution has O(N²) time complexity compared to the naive O(N²M²) approach. Space complexity is O(N²) for storing column sums.
Conclusion
This algorithm efficiently finds the maximum sum sub-matrix using sliding window technique. It optimizes time complexity by pre-computing column sums and reusing them for row-wise calculations.
Advertisements
