Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | Python3 implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculating prefix sum ; Checking whether there exits square with length cur_max + 1 or not ; Returning the maximum length ; Driver code
import numpy as np NEW_LINE def maxLengthSquare ( row , column , arr , k ) : NEW_LINE INDENT sum = np . zeros ( ( row + 1 , column + 1 ) ) ; NEW_LINE cur_max = 1 ; NEW_LINE max = 0 ; NEW_LINE for i in range ( 1 , row + 1 ) : NEW_LINE INDENT for j in range ( 1 , column + 1 ) : NEW_LINE INDENT sum [ i ] [ j ] = sum [ i - 1 ] [ j ] + sum [ i ] [ j - 1 ] + arr [ i - 1 ] [ j - 1 ] - sum [ i - 1 ] [ j - 1 ] ; NEW_LINE 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 ) : NEW_LINE INDENT max = cur_max ; NEW_LINE cur_max += 1 ; NEW_LINE DEDENT DEDENT DEDENT return max ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT row = 4 ; NEW_LINE column = 4 ; NEW_LINE matrix = [ [ 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] ] ; NEW_LINE k = 6 ; NEW_LINE ans = maxLengthSquare ( row , column , matrix , k ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT