Maximum size of square such that all submatrices of that size have sum less than K
Last Updated :
12 Jul, 2025
Given an N x M matrix of integers and an integer K, the task is to find the size of the maximum square sub-matrix (S x S), such that all square sub-matrices of the given matrix of that size have a sum less than K.
Examples:
Input: K = 30
mat[N][M] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
Output: 2
Explanation:
All Sub-matrices of size 2 x 2
have sum less than 30
Input : K = 100
mat[N][M] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
Output: 3
Explanation:
All Sub-matrices of size 3 x 3
have sum less than 100
Naive Approach The basic solution is to choose the size S of the submatrix and find all the submatrices of that size and check that the sum of all sub-matrices is less than the given sum whereas, this can be improved by computing the sum of the matrix using this approach. Therefore, the task will be to choose the maximum size possible and the starting and ending position of every possible sub-matrices. Due to which the overall time complexity will be O(N3).
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// maximum size square submatrix
// such that their sum is less than K
#include <bits/stdc++.h>
using namespace std;
// Size of matrix
#define N 4
#define M 5
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
void preProcess(int mat[N][M],
int aux[N][M])
{
// Loop to copy the first row
// of the matrix into the aux matrix
for (int i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for (int i = 1; i < N; i++)
for (int j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for (int i = 0; i < N; i++)
for (int j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
int sumQuery(int aux[N][M], int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res +
aux[tli - 1][tlj - 1];
return res;
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
int maximumSquareSize(int mat[N][M], int K)
{
int aux[N][M];
preProcess(mat, aux);
// Loop to choose the size of matrix
for (int i = min(N, M); i >= 1; i--) {
bool satisfies = true;
// Loop to find the sum of the
// matrix of every possible submatrix
for (int x = 0; x < N; x++) {
for (int y = 0; y < M; y++) {
if (x + i - 1 <= N - 1 &&
y + i - 1 <= M - 1) {
if (sumQuery(aux, x, y,
x + i - 1, y + i - 1) > K)
satisfies = false;
}
}
}
if (satisfies == true)
return (i);
}
return 0;
}
// Driver Code
int main()
{
int K = 30;
int mat[N][M] = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
cout << maximumSquareSize(mat, K);
return 0;
}
Java
// Java implementation to find the
// maximum size square submatrix
// such that their sum is less than K
class GFG{
// Size of matrix
static final int N = 4;
static final int M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
static void preProcess(int [][]mat,
int [][]aux)
{
// Loop to copy the first row
// of the matrix into the aux matrix
for (int i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for (int i = 1; i < N; i++)
for (int j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for (int i = 0; i < N; i++)
for (int j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
static int sumQuery(int [][]aux, int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res +
aux[tli - 1][tlj - 1];
return res;
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
static int maximumSquareSize(int [][]mat, int K)
{
int [][]aux = new int[N][M];
preProcess(mat, aux);
// Loop to choose the size of matrix
for (int i = Math.min(N, M); i >= 1; i--) {
boolean satisfies = true;
// Loop to find the sum of the
// matrix of every possible submatrix
for (int x = 0; x < N; x++) {
for (int y = 0; y < M; y++) {
if (x + i - 1 <= N - 1 &&
y + i - 1 <= M - 1) {
if (sumQuery(aux, x, y,
x + i - 1, y + i - 1) > K)
satisfies = false;
}
}
}
if (satisfies == true)
return (i);
}
return 0;
}
// Driver Code
public static void main(String[] args)
{
int K = 30;
int mat[][] = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
System.out.print(maximumSquareSize(mat, K));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 implementation to find the
# maximum size square submatrix
# such that their sum is less than K
# Size of matrix
N = 4
M = 5
# Function to preprocess the matrix
# for computing the sum of every
# possible matrix of the given size
def preProcess(mat, aux):
# Loop to copy the first row
# of the matrix into the aux matrix
for i in range (M):
aux[0][i] = mat[0][i]
# Computing the sum column-wise
for i in range (1, N):
for j in range (M):
aux[i][j] = (mat[i][j] +
aux[i - 1][j])
# Computing row wise sum
for i in range (N):
for j in range (1, M):
aux[i][j] += aux[i][j - 1]
# Function to find the sum of a
# submatrix with the given indices
def sumQuery(aux, tli, tlj, rbi, rbj):
# Overall sum from the top to
# right corner of matrix
res = aux[rbi][rbj]
# Removing the sum from the top
# corer of the matrix
if (tli > 0):
res = res - aux[tli - 1][rbj]
# Remove the overlapping sum
if (tlj > 0):
res = res - aux[rbi][tlj - 1]
# Add the sum of top corner
# which is subtracted twice
if (tli > 0 and tlj > 0):
res = (res +
aux[tli - 1][tlj - 1])
return res
# Function to find the maximum
# square size possible with the
# such that every submatrix have
# sum less than the given sum
def maximumSquareSize(mat, K):
aux = [[0 for x in range (M)]
for y in range (N)]
preProcess(mat, aux)
# Loop to choose the size of matrix
for i in range (min(N, M), 0, -1):
satisfies = True
# Loop to find the sum of the
# matrix of every possible submatrix
for x in range (N):
for y in range (M) :
if (x + i - 1 <= N - 1 and
y + i - 1 <= M - 1):
if (sumQuery(aux, x, y,
x + i - 1,
y + i - 1) > K):
satisfies = False
if (satisfies == True):
return (i)
return 0
# Driver Code
if __name__ == "__main__":
K = 30
mat = [[1, 2, 3, 4, 6],
[5, 3, 8, 1, 2],
[4, 6, 7, 5, 5],
[2, 4, 8, 9, 4]]
print( maximumSquareSize(mat, K))
# This code is contributed by Chitranayal
C#
// C# implementation to find the
// maximum size square submatrix
// such that their sum is less than K
using System;
public class GFG{
// Size of matrix
static readonly int N = 4;
static readonly int M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
static void preProcess(int [,]mat,
int [,]aux)
{
// Loop to copy the first row
// of the matrix into the aux matrix
for (int i = 0; i < M; i++)
aux[0,i] = mat[0,i];
// Computing the sum column-wise
for (int i = 1; i < N; i++)
for (int j = 0; j < M; j++)
aux[i,j] = mat[i,j] +
aux[i - 1,j];
// Computing row wise sum
for (int i = 0; i < N; i++)
for (int j = 1; j < M; j++)
aux[i,j] += aux[i,j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
static int sumQuery(int [,]aux, int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi,rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1,rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi,tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res +
aux[tli - 1,tlj - 1];
return res;
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
static int maximumSquareSize(int [,]mat, int K)
{
int [,]aux = new int[N,M];
preProcess(mat, aux);
// Loop to choose the size of matrix
for (int i = Math.Min(N, M); i >= 1; i--) {
bool satisfies = true;
// Loop to find the sum of the
// matrix of every possible submatrix
for (int x = 0; x < N; x++) {
for (int y = 0; y < M; y++) {
if (x + i - 1 <= N - 1 &&
y + i - 1 <= M - 1) {
if (sumQuery(aux, x, y,
x + i - 1, y + i - 1) > K)
satisfies = false;
}
}
}
if (satisfies == true)
return (i);
}
return 0;
}
// Driver Code
public static void Main(String[] args)
{
int K = 30;
int [,]mat = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
Console.Write(maximumSquareSize(mat, K));
}
}
// This code contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript implementation to find the
// maximum size square submatrix
// such that their sum is less than K
// Size of matrix
let N = 4;
let M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
function preProcess(mat,aux)
{
// Loop to copy the first row
// of the matrix into the aux matrix
for (let i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for (let i = 1; i < N; i++)
for (let j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for (let i = 0; i < N; i++)
for (let j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
function sumQuery(aux,tli,tlj,rbi,rbj)
{
// Overall sum from the top to
// right corner of matrix
let res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res +
aux[tli - 1][tlj - 1];
return res;
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
function maximumSquareSize(mat,k)
{
let aux = new Array(N);
for(let i=0;i<N;i++)
{
aux[i]=new Array(M);
}
preProcess(mat, aux);
// Loop to choose the size of matrix
for (let i = Math.min(N, M); i >= 1; i--) {
let satisfies = true;
// Loop to find the sum of the
// matrix of every possible submatrix
for (let x = 0; x < N; x++) {
for (let y = 0; y < M; y++) {
if (x + i - 1 <= N - 1 &&
y + i - 1 <= M - 1) {
if (sumQuery(aux, x, y,
x + i - 1, y + i - 1) > K)
satisfies = false;
}
}
}
if (satisfies == true)
return (i);
}
return 0;
}
// Driver Code
let mat = [[1, 2, 3, 4, 6],
[5, 3, 8, 1, 2],
[4, 6, 7, 5, 5],
[2, 4, 8, 9, 4]];
let K = 30;
document.write(maximumSquareSize(mat, K));
// This code is contributed by avanitrachhadiya2155
</script>
- Time complexity: O(N3)
- Auxiliary Space: O(N2)
Efficient Approach: The key observation is, if a square of side s is the maximum size satisfying the condition, then all sizes smaller than it will satisfy the condition. Using this we can reduce our search space at each step by half which is precisely the idea of Binary Search. Below is the illustration of the steps of the approach:
- Search Space: The search space for this problem will be from [1, min(N, M)]. That is the search space for binary search is defined as -
low = 1
high = min(N, M)
- Next Search Space: In each iteration find the mid of the search space and then Finally, check that all subarrays of that size have the sum less than K. If all subarrays of that size have sum less than K. Then the next search space possible will be in the right of the middle. Otherwise, the next search space possible will be in the left of the middle. That is less than the middle.
- Case 1: Condition when the all the subarrays of size mid have sum less than K. Then -
if checkSubmatrix(mat, mid, K):
low = mid + 1
- Case 2: Condition when the all the subarrays of size mid have sum greater than K. Then -
if not checkSubmatrix(mat, mid, K):
high = mid - 1
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// maximum size square submatrix
// such that their sum is less than K
#include <bits/stdc++.h>
using namespace std;
// Size of matrix
#define N 4
#define M 5
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
void preProcess(int mat[N][M],
int aux[N][M])
{
// Loop to copy the first row
// of the matrix into the aux matrix
for (int i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for (int i = 1; i < N; i++)
for (int j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for (int i = 0; i < N; i++)
for (int j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
int sumQuery(int aux[N][M], int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli - 1][tlj - 1];
return res;
}
// Function to check whether square
// sub matrices of size mid satisfy
// the condition or not
bool check(int mid, int aux[N][M],
int K)
{
bool satisfies = true;
// Iterating through all possible
// submatrices of given size
for (int x = 0; x < N; x++) {
for (int y = 0; y < M; y++) {
if (x + mid - 1 <= N - 1 &&
y + mid - 1 <= M - 1) {
if (sumQuery(aux, x, y,
x + mid - 1, y + mid - 1) > K)
satisfies = false;
}
}
}
return (satisfies == true);
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
int maximumSquareSize(int mat[N][M],
int K)
{
int aux[N][M];
preProcess(mat, aux);
// Search space
int low = 1, high = min(N, M);
int mid;
// Binary search for size
while (high - low > 1) {
mid = (low + high) / 2;
// Check if the mid satisfies
// the given condition
if (check(mid, aux, K)) {
low = mid;
}
else
high = mid;
}
if (check(high, aux, K))
return high;
return low;
}
// Driver Code
int main()
{
int K = 30;
int mat[N][M] = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
cout << maximumSquareSize(mat, K);
return 0;
}
Java
// Java implementation to find the
// maximum size square submatrix
// such that their sum is less than K
class GFG{
// Size of matrix
static final int N = 4;
static final int M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
static void preProcess(int [][]mat,
int [][]aux)
{
// Loop to copy the first row of
// the matrix into the aux matrix
for(int i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for(int i = 1; i < N; i++)
for(int j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for(int i = 0; i < N; i++)
for(int j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
static int sumQuery(int [][]aux, int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli - 1][tlj - 1];
return res;
}
// Function to check whether square
// sub matrices of size mid satisfy
// the condition or not
static boolean check(int mid, int [][]aux,
int K)
{
boolean satisfies = true;
// Iterating through all possible
// submatrices of given size
for(int x = 0; x < N; x++)
{
for(int y = 0; y < M; y++)
{
if (x + mid - 1 <= N - 1 &&
y + mid - 1 <= M - 1)
{
if (sumQuery(aux, x, y,
x + mid - 1,
y + mid - 1) > K)
satisfies = false;
}
}
}
return (satisfies == true);
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
static int maximumSquareSize(int [][]mat,
int K)
{
int [][]aux = new int[N][M];
preProcess(mat, aux);
// Search space
int low = 1, high = Math.min(N, M);
int mid;
// Binary search for size
while (high - low > 1)
{
mid = (low + high) / 2;
// Check if the mid satisfies
// the given condition
if (check(mid, aux, K))
{
low = mid;
}
else
high = mid;
}
if (check(high, aux, K))
return high;
return low;
}
// Driver Code
public static void main(String[] args)
{
int K = 30;
int [][]mat = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
System.out.print(maximumSquareSize(mat, K));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 implementation to find the
# maximum size square submatrix
# such that their sum is less than K
# Function to preprocess the matrix
# for computing the sum of every
# possible matrix of the given size
def preProcess(mat, aux):
# Loop to copy the first row
# of the matrix into the aux matrix
for i in range(5):
aux[0][i] = mat[0][i]
# Computing the sum column-wise
for i in range(1, 4):
for j in range(5):
aux[i][j] = (mat[i][j] +
aux[i - 1][j])
# Computing row wise sum
for i in range(4):
for j in range(1, 5):
aux[i][j] += aux[i][j - 1]
return aux
# Function to find the sum of a
# submatrix with the given indices
def sumQuery(aux, tli, tlj, rbi, rbj):
# Overall sum from the top to
# right corner of matrix
res = aux[rbi][rbj]
# Removing the sum from the top
# corer of the matrix
if (tli > 0):
res = res - aux[tli - 1][rbj]
# Remove the overlapping sum
if (tlj > 0):
res = res - aux[rbi][tlj - 1]
# Add the sum of top corner
# which is subtracted twice
if (tli > 0 and tlj > 0):
res = res + aux[tli - 1][tlj - 1]
return res
# Function to check whether square
# sub matrices of size mid satisfy
# the condition or not
def check(mid, aux, K):
satisfies = True
# Iterating through all possible
# submatrices of given size
for x in range(4):
for y in range(5):
if (x + mid - 1 <= 4 - 1 and
y + mid - 1 <= 5 - 1):
if (sumQuery(aux, x, y,
x + mid - 1,
y + mid - 1) > K):
satisfies = False
return True if satisfies == True else False
# Function to find the maximum
# square size possible with the
# such that every submatrix have
# sum less than the given sum
def maximumSquareSize(mat, K):
aux = [[0 for i in range(5)]
for i in range(4)]
aux = preProcess(mat, aux)
# Search space
low , high = 1, min(4, 5)
mid = 0
# Binary search for size
while (high - low > 1):
mid = (low + high) // 2
# Check if the mid satisfies
# the given condition
if (check(mid, aux, K)):
low = mid
else:
high = mid
if (check(high, aux, K)):
return high
return low
# Driver Code
if __name__ == '__main__':
K = 30
mat = [ [ 1, 2, 3, 4, 6 ],
[ 5, 3, 8, 1, 2 ],
[ 4, 6, 7, 5, 5 ],
[ 2, 4, 8, 9, 4 ] ]
print(maximumSquareSize(mat, K))
# This code is contributed by mohit kumar 29
C#
// C# implementation to find the
// maximum size square submatrix
// such that their sum is less than K
using System;
class GFG{
// Size of matrix
static readonly int N = 4;
static readonly int M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
static void preProcess(int [,]mat,
int [,]aux)
{
// Loop to copy the first row of
// the matrix into the aux matrix
for(int i = 0; i < M; i++)
aux[0, i] = mat[0, i];
// Computing the sum column-wise
for(int i = 1; i < N; i++)
for(int j = 0; j < M; j++)
aux[i, j] = mat[i, j] +
aux[i - 1, j];
// Computing row wise sum
for(int i = 0; i < N; i++)
for(int j = 1; j < M; j++)
aux[i, j] += aux[i, j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
static int sumQuery(int [,]aux, int tli,
int tlj, int rbi, int rbj)
{
// Overall sum from the top to
// right corner of matrix
int res = aux[rbi, rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1, rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi, tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli - 1, tlj - 1];
return res;
}
// Function to check whether square
// sub matrices of size mid satisfy
// the condition or not
static bool check(int mid, int [,]aux,
int K)
{
bool satisfies = true;
// Iterating through all possible
// submatrices of given size
for(int x = 0; x < N; x++)
{
for(int y = 0; y < M; y++)
{
if (x + mid - 1 <= N - 1 &&
y + mid - 1 <= M - 1)
{
if (sumQuery(aux, x, y,
x + mid - 1,
y + mid - 1) > K)
satisfies = false;
}
}
}
return (satisfies == true);
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
static int maximumSquareSize(int [,]mat,
int K)
{
int [,]aux = new int[N, M];
preProcess(mat, aux);
// Search space
int low = 1, high = Math.Min(N, M);
int mid;
// Binary search for size
while (high - low > 1)
{
mid = (low + high) / 2;
// Check if the mid satisfies
// the given condition
if (check(mid, aux, K))
{
low = mid;
}
else
high = mid;
}
if (check(high, aux, K))
return high;
return low;
}
// Driver Code
public static void Main(String[] args)
{
int K = 30;
int [,]mat = { { 1, 2, 3, 4, 6 },
{ 5, 3, 8, 1, 2 },
{ 4, 6, 7, 5, 5 },
{ 2, 4, 8, 9, 4 } };
Console.Write(maximumSquareSize(mat, K));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript implementation to find the
// maximum size square submatrix
// such that their sum is less than K
// Size of matrix
let N = 4;
let M = 5;
// Function to preprocess the matrix
// for computing the sum of every
// possible matrix of the given size
function preProcess(mat,aux)
{
// Loop to copy the first row of
// the matrix into the aux matrix
for(let i = 0; i < M; i++)
aux[0][i] = mat[0][i];
// Computing the sum column-wise
for(let i = 1; i < N; i++)
for(let j = 0; j < M; j++)
aux[i][j] = mat[i][j] +
aux[i - 1][j];
// Computing row wise sum
for(let i = 0; i < N; i++)
for(let j = 1; j < M; j++)
aux[i][j] += aux[i][j - 1];
}
// Function to find the sum of a
// submatrix with the given indices
function sumQuery(aux,tli,tlj,rbi,rbj)
{
// Overall sum from the top to
// right corner of matrix
let res = aux[rbi][rbj];
// Removing the sum from the top
// corer of the matrix
if (tli > 0)
res = res - aux[tli - 1][rbj];
// Remove the overlapping sum
if (tlj > 0)
res = res - aux[rbi][tlj - 1];
// Add the sum of top corner
// which is subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli - 1][tlj - 1];
return res;
}
// Function to check whether square
// sub matrices of size mid satisfy
// the condition or not
function check(mid,aux,K)
{
let satisfies = true;
// Iterating through all possible
// submatrices of given size
for(let x = 0; x < N; x++)
{
for(let y = 0; y < M; y++)
{
if (x + mid - 1 <= N - 1 &&
y + mid - 1 <= M - 1)
{
if (sumQuery(aux, x, y,
x + mid - 1,
y + mid - 1) > K)
satisfies = false;
}
}
}
return (satisfies == true);
}
// Function to find the maximum
// square size possible with the
// such that every submatrix have
// sum less than the given sum
function maximumSquareSize(mat,K)
{
let aux = new Array(N);
for(let i=0;i<N;i++)
{
aux[i]=new Array(M);
}
preProcess(mat, aux);
// Search space
let low = 1, high = Math.min(N, M);
let mid;
// Binary search for size
while (high - low > 1)
{
mid = Math.floor((low + high) / 2);
// Check if the mid satisfies
// the given condition
if (check(mid, aux, K))
{
low = mid;
}
else
high = mid;
}
if (check(high, aux, K))
return high;
return low;
}
// Driver Code
let K = 30;
let mat = [[1, 2, 3, 4, 6 ],
[ 5, 3, 8, 1, 2 ],
[ 4, 6, 7, 5, 5 ],
[ 2, 4, 8, 9, 4 ] ];
document.write(maximumSquareSize(mat, K));
// This code is contributed by rag2127
</script>
Performance Analysis:
- Time Complexity: O(N2 * log(N) )
- Auxiliary Space: O(N2)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem