Given a N x M matrix where N is the number of rows and M is the number of columns in the given matrix and an integer K. The task is to find maximum length of a square submatrix having sum of elements less than or equal to K or print 0 if no such square exits.
Examples:
Input: r = 4, c = 4 , k = 6
matrix[][] = { {1, 1, 1, 1},
{1, 0, 0, 0},
{1, 0, 0, 0},
{1, 0, 0, 0},
}
Output: 3
Explanation:
Square from (0,0) to (2,2) with
sum 5 is one of the valid answer.
Input: r = 4, c = 4 , k = 1
matrix[][] = { {2, 2, 2},
{2, 2, 2},
{2, 2, 2},
{2, 2, 2},
}
Output: 0
Explanation:
There is no valid answer.
Approach:
The idea is to calculate prefix sum matrix. Once the prefix sum matrix is calculated, required sub-matrix sum can be calculate in O(1) time complexity. Use sliding window technique to calculate the maximum length square submatrix. For every square of length cur_max+1, where cur_max is the currently found maximum length of a square submatrix, we check whether the sum of elements in the current submatrix, having length of cur_max+1, is less than or equal to K or not. If yes than increase the result by 1 otherwise we continue to check.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach #include <iostream> using namespace std; // Function to return maximum // length of square submatrix // having sum of elements at-most K int maxLengthSquare(int row, int column, int arr[][4], int k) { // Matrix to store prefix sum int sum[row + 1][column + 1] ; for(int i = 1; i <= row; i++) for(int j = 0; j <= column; j++) sum[i][j] = 0; // Current maximum length int cur_max = 1; // Variable for storing // maximum length of square int max = 0; for (int i = 1; i <= row; i++) { for (int j = 1; j <= column; j++) { // Calculating prefix sum sum[i][j] = sum[i - 1][j] + sum[i][j - 1] + arr[i - 1][j - 1] - sum[i - 1][j - 1]; // Checking whether there // exits square with length // cur_max+1 or not if(i >= cur_max && j >= cur_max && sum[i][j] - sum[i - cur_max][j] - sum[i][j - cur_max] + sum[i - cur_max][j - cur_max] <= k) { max = cur_max++; } } } // Returning the // maximum length return max; } // Driver code int main() { int row = 4, column = 4; int matrix[4][4] = { {1, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0} }; int k = 6; int ans = maxLengthSquare(row, column, matrix, k); cout << ans; return 0; } // This code is contributed by AnkitRai01 |
Java
// Java implementation of // the above approach import java.util.*; class GFG { // Function to return maximum // length of square submatrix // having sum of elements at-most K public static int maxLengthSquare(int row,int column, int[][] arr, int k) { // Matrix to store prefix sum int sum[][] = new int[row + 1][column + 1]; // Current maximum length int cur_max = 1; // Variable for storing // maximum length of square int max = 0; for (int i = 1; i <= row; i++) { for (int j = 1; j <= column; j++) { // Calculating prefix sum sum[i][j] = sum[i - 1][j] + sum[i][j - 1] + arr[i - 1][j - 1] - sum[i - 1][j - 1]; // Checking whether there // exits square with length // cur_max+1 or not if(i >=cur_max&&j;>=cur_max&∑[i][j]-sum[i - cur_max][j] - sum[i][j - cur_max] + sum[i - cur_max][j - cur_max] <= k){ max = cur_max++; } } } // Returning the // maximum length return max; } // Driver code public static void main(String args[]) { int row = 4 , column = 4; int matrix[][] = { {1, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0} }; int k = 6; int ans = maxLengthSquare(row,column,matrix, k); System.out.println(ans); } } |
Python3
# Python3 implementation of the above approach import numpy as np # Function to return maximum # length of square submatrix # having sum of elements at-most K def maxLengthSquare(row, column, arr, k) : # Matrix to store prefix sum sum = np.zeros((row + 1, column + 1)); # Current maximum length cur_max = 1; # Variable for storing # maximum length of square max = 0; for i in range(1, row + 1) : for j in range(1, column + 1) : # Calculating prefix sum sum[i][j] = sum[i - 1][j] + sum[i][j - 1] + \ arr[i - 1][j - 1] - \ sum[i - 1][j - 1]; # Checking whether there # exits square with length # cur_max+1 or not if(i >= cur_max and j >= cur_max and sum[i][j] - sum[i - cur_max][j] - sum[i][j - cur_max] + sum[i - cur_max][j - cur_max] <= k) : max = cur_max; cur_max += 1; # Returning the maximum length return max; # Driver code if __name__ == "__main__" : row = 4 ; column = 4; matrix = [[1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]; k = 6; ans = maxLengthSquare(row, column, matrix, k); print(ans); # This code is contributed by AnkitRai01 |
C#
// C# implementation of the above approach using System; class GFG { // Function to return maximum // length of square submatrix // having sum of elements at-most K public static int maxLengthSquare(int row,int column, int[,] arr, int k) { // Matrix to store prefix sum int [,]sum = new int[row + 1,column + 1]; // Current maximum length int cur_max = 1; // Variable for storing // maximum length of square int max = 0; for (int i = 1; i <= row; i++) { for (int j = 1; j <= column; j++) { // Calculating prefix sum sum[i, j] = sum[i - 1, j] + sum[i, j - 1] + arr[i - 1, j - 1] - sum[i - 1, j - 1]; // Checking whether there // exits square with length // cur_max+1 or not if(i >=cur_max && j>=cur_max && sum[i, j]-sum[i - cur_max, j] - sum[i, j - cur_max] + sum[i - cur_max, j - cur_max] <= k) { max = cur_max++; } } } // Returning the // maximum length return max; } // Driver code public static void Main() { int row = 4 , column = 4; int [,]matrix = { {1, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0} }; int k = 6; int ans = maxLengthSquare(row, column, matrix, k); Console.WriteLine(ans); } } // This code is contributed by AnkitRai01 |
3
Time Complexity: O(N x M)
Recommended Posts:
- Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
- Largest possible square submatrix with maximum AND value
- Longest Subarray having sum of elements atmost 'k'
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Min and max length subarray having adjacent element difference atmost K
- Maximum sum of non-overlapping subarrays of length atmost K
- Check if a matrix contains a square submatrix with 0 as boundary element
- Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Longest Increasing Subsequence having sum value atmost K
- Maximize sum of atmost K elements in array by taking only corner elements | Set 2
- Length of Longest Subarray with same elements in atmost K increments
- Count of subsequences of length atmost K containing distinct prime elements
- Find the length of the longest subarray with atmost K occurrences of the integer X
- Maximum value in a matrix which contain intersecting concentric submatrix
- Submatrix of given size with maximum 1's
- Smallest submatrix with Kth maximum XOR
- Check if matrix A can be converted to B by changing parity of corner elements of any submatrix
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Longest subsequence having difference atmost K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01


