Find maximum sum submatrix in a given matrix in c In this article, we will learn how we can find the maximum value in an array in C. Jul 23, 2025 · Using Recursion - O (3^ (n+m)) Time and O (n+m) Space The idea is to recursively determine the side length of the largest square sub-matrix with all 1s at each cell. The task is to calculate the maximum sum of the upper-left N X N submatrix i. Please Like, Can you solve this real interview question? Number of Submatrices That Sum to Target - Given a matrix and a target, return the number of non-empty submatrices that sum to target. This guide provides detailed examples and explanations for better understanding. Sep 27, 2012 · Possible Duplicate: Getting the submatrix with maximum sum? Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. Jul 5, 2022 · Given a matrix with integer elements the problem is to find the maximum sum submatrix. A sub-matrix is nothing but a 2D array inside of the given 2D array. Mar 23, 2011 · Possible Duplicate: Finding a submatrix with the maximum possible sum in O(n^2) I have an NxN matrix. Sep 18, 2025 · Given an `M × N` matrix and two coordinates `(p, q)` and `(r, s)` representing top-left and bottom-right coordinates of a submatrix of it, calculate the sum of all elements present in the submatrix. What will be good way of finding the sub matrix with the largest sum and this sub matrix may not be contiguous such that you can select columns 1 and 3 and rows 1 and 3 and leave out column 2 and row 2? Any hints/suggestions/tricks will help a lot. Oct 16, 2024 · This issue has been addressed by providing a solution to the problem of finding the submatrix with the maximum sum in a given 2D matrix of size N x N. The smallest numbers will Apr 12, 2017 · Define a new matrix A wich will store in A [i,j] two values: the width and the height of the largest submatrix with the left upper corner at i,j, fill this matrix starting from the bottom right corner, by rows bottom to top. Sep 13, 2023 · Given a 2N x 2N matrix of integers. Then the two inner loops should iterate over the 3 rows and 3 columns of the submatrix that starts there. For each such 1D array, maintain a running sum and use a hash map to count how many times a particular prefix sum has occurred. The algorithm has a time complexity of Apr 28, 2025 · The idea is to calculate the contribution of each element to the total sum by determining in how many different submatrices that element appears. Find a submatrix such that the sum of its elements is maximum and return this sum. We can do this by taking the sum row wise first and then column wise (we can do vice versa too). We can directly compute how many submatrices contain each element in O (1) time and use this to find each element's total contribution to the sum. For example, the maximum sum submatrix is highlighted in green in the following matrices. Finally, print the maximum sum of such submatrices obtained. Examples: Input : mat [] [] = { 112, 42, 83, 119, 56, 125, 56, 49, 15, 78, 101, 43, 62, 98, 114, 108 } Output : 414 Given matrix Overview The Kadane's algorithm is a well-known method for solving the problem of finding the maximum sum of a contiguous subarray of a given array of numbers. Submatrix: In this problem, a submatrix is defined as a rectangle, which can be obtained by deleting a certain number of boundary rows and columns from the given original matrix. Jan 14, 2024 · Given a matrix A of size NxM, which is row-wise and column-wise sorted. We need to find a rectangle (sometimes square) matrix, whose sum is maximum. Solution The brute force approach is to get all sub-matrices, calculate the sum and update the max-sum as we go on. A binary matrix is a two-dimensional array having values only 0 and 1. For each prefix sum, you'll consider the lowest prefix sum that precedes it and calculate the difference (picking the lowest because you need to maximise the difference). Sep 18, 2025 · Given an `N × N` matrix, find the maximum sum submatrix present in it. calculateSubMatrixSum Function: This function calculates the sum of elements within a given submatrix specified by its starting and ending rows and columns. You are allowed to reverse any row or column any number of times and in any order. We use min to keep a track of Problem Statement Find the maximum sum rectangle in a 2D matrix i. The sum of a rectangle is the sum of all the elements in that rectangle. For example, if you have a matrix and k = 2, you . Traverse the matrix row-wise using i as the row index and j as the column index and perform the following steps: Sep 18, 2025 · Given an `M × N` matrix, calculate the maximum sum submatrix of size `k × k` in it in `O(M × N)` time. If there is one row only or one column only, then this is equivalent to finding a maximum sub-array. Oct 26, 2018 · It will be easier if you replace your outer loop with two outer loops: one for what the first row will be of the submatrix, and another for its first column. So temp [i] indicates the sum of elements from left to right in row i. Note: A subarray is a continuous part of an array. Can you solve this real interview question? Maximum Matrix Sum - You are given an n x n integer matrix. First create a Jul 12, 2025 · Find the middle index (say mid). permutation or combination. e. The function should return the row and column indices of where the submatrix starts, the dimensions of the submatrix and the sum of the submatrix. In this blog post, we discussed how to find the maximum sum submatrix in a given m x n grid. g. Also read - Decimal to Binary c++ Algorithm Let the Given:A Matrix (Not necessarily square) filled with negative and positive integers. We will try to find top and bottom row numbers. We explored the problem, understood the challenges, and developed an efficient solution using prefix sums and Kadane's algorithm. The smallest numbers will be on the top Jul 23, 2025 · Given a 2d array mat [] [] of order n * n, and an integer k. to find a sub-matrix with maximum sum. Input The first line of the input contains two integers - the number of rows in the matrix r and the number of columns c (1 ≤ r, c ≤ 50). Jun 13, 2023 · The goal of the game is to maximize the sum of the elements in the n x n submatrix located in the upper- left quadrant of the matrix. Find the maximum sum submatrix in it. Oct 3, 2025 · Create a matrix prefMatrix [N] [M] that stores the prefix array sum of every row of the given matrix. It is guaranteed that there will be a rectangle with a sum no larger than k. We need to find the size of a small square matrix formed by only 1 in this binary matrix. cod Jan 16, 2024 · Given a 2D integer matrix A of size N x N find a B x B submatrix where B <= N and B >= 1, such that sum of all the elements in submatrix is maximum. Sep 16, 2022 · Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S. After getting the temporary array, we can apply the Kadane’s Dec 20, 2022 · We basically find top and bottom row numbers (which have minimum sum) for every fixed left and right column pair. Find a submatrix such that sum of its elements is maximum and return this sum. So, before we dive down first, we should know about the binary matrix. The 2D matrix is made up of integers, and the goal is to find the subarray with the largest possible sum that is ≤ k. 📍Join my paid Java DSA course here: https://www. A submatrix x1, y1, x2, y2 is the set of all cells matrix [x] [y] with x1 <= x <= x2 and y1 <= y <= y2. The next r lines contain c integers separated by a space, that represent the elements in the matrix (10 9 <m i, j <10 9) (−109 <mi Nov 24, 2024 · Now, we have to find the maximum sum of all the elements in the matrix. Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find out. Maximum subarray in left and right half can be found easily by two recursive calls. Mar 27, 2024 · Introduction In this blog, we will learn how to find the square maximum submatrix of all 1's in a binary matrix. If found to be true, store the sum of that submatrix. A common pitfall is to assume that the submatrix must be contiguous in both rows and The core challenge of this problem is to find the submatrix within a given m x n grid that has the maximum sum. Find Complete Code at GeeksforGeeks Article: https://www. A matrix is given. Jan 25, 2022 · Learn how to find a sub-matrix with a given sum using C++. Better than official and forum solutions. InterviewBit SOLUTION We will create a prefix sum for the matrix. All elements of the rectangle need to be contiguous either row-wise or column-wise. You might explain what application you have in mind for these submatrices, as it could affect how to count, e. Requirement: Algorithm complexity to be of O (N^3) History: With the help of the Algorithmist, Larry and a modification of Kadane's Algorithm, i managed to solve the problem partly which is determining the Aug 22, 2019 · Learn how to print the maximum sum square sub-matrix of a given size using C programming with this comprehensive guide. e the sum of elements of the submatrix from (0, 0) to (N - 1, N - 1). Then, the sum of any subarray will be: In-depth solution and explanation for LeetCode 1975. Jul 23, 2025 · Output: 3 Explanation: The maximum sum rectangle is { {2, 2, -1}} is 3 ( <- K). Problem Description: The task is to Problem Description You are given an m x n matrix filled with integers and a target value k. Your task is to find a rectangle (submatrix) within this matrix that has the maximum possible sum, with the constraint that this sum must not exceed k. You can do the following operation any number of times: * Choose any two adjacent elements of matrix and multiply each of them by -1. To find the top and bottom row numbers, calculate the sum of elements in every row from left to right and store these sums in an array say temp []. Apr 1, 2020 · Ordinarily when we ask for a submatrix it means a subset of the rows and a subset of the columns from the original matrix, arranged in the same order of appearance. int Jun 29, 2023 · PROBLEM STATEMENT Given a matrix A of size NxM, which is row-wise and column-wise sorted. APPROACH: 1. Intuitions, example walk through, and complexity analysis. This problem is significant in various applications such as image processing, financial analysis, and more. Jul 4, 2022 · Problem Description Given a 2D matrix, find the maximum possible sum of sub-matrices in that matrix. Given a 2D integer array (matrix), find the submatrix with the largest sum of its elements. Given a $n\times m$ matrix $A$ of integers, find a sub-matrix whose sum is maximal. Jul 28, 2025 · Given a 2D matrix mat [] [] of integers, find the submatrix (i. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. Your goal is to maximize the summation of the matrix's elements. The basic idea behind the algorithm is to iterate through the array, keeping track of the maximum sum seen so far and the current sum, and updating the maximum sum whenever a new maximum is found. Jul 23, 2025 · Divide the given array in two halves and return the maximum of following three: Maximum subarray sum in left half. Then, for every pair of columns i and j, reduce the matrix to a 1D array by summing values in each row between columns i and j. Otherwise, we calculate the possible side length of a square ending at this cell by finding the minimum square side lengths from the right Mar 17, 2025 · Each submatrix calculates the sum of its elements using the calculateSubMatrixSum function and updates the maximum sum if the calculated sum is greater than the current maximum. Return the maximum Jul 26, 2025 · Compute prefix sums row-wise to allow quick calculation of horizontal subarray sums. Maximum subarray sum in right half. For example, consider the following `5 × 5` matrix. geeksforgeeks. Given the initial configurations for a matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix’s upper- left quadrant is maximal Maximum submatrix Given an r × c r×c matrix of integers, you are asked to calculate the submatrix with the maximum sum. Parameters: — `array`: Reference to a vector Aug 24, 2024 · This problem challenges us to find the submatrix with the maximum sum within a given matrix, with the submatrix being of a fixed size. The problem guarantees that at least one valid rectangle exists with a sum less than or equal to k. Maximum subarray sum such that the subarray crosses the midpoint. Feb 17, 2010 · In an interview I was asked if I was given an n*m matrix how to calculate the sum of the values in a given sub-matrix (defined by top-left, bottom-right coordinates). For each cell, if its value is 0, we return 0 since it cannot contribute to a square. Else Update the upper limit as mid - 1 to find the maximum sum with size less than mid. You need to implement a divide and conquer algorithm to solve this problem. Your task is to find a submatrix of order k * k, such that sum of all the elements in the submatrix is maximum possible. Jul 2, 2021 · Given a matrix mat [] [] whose elements are sorted both row-wise and column-wise. Dec 7, 2015 · The aim of the exercise is to find the submatrix of matrix A that has the highest sum. So, you have a matrix of signed integers, you need to calculate the sum of sub-matrices and find the maximum value. We have to maximize this sum by reversing the sign of two adjacent matrix elements, that is, multiply these adjacent Jul 23, 2025 · In C, arrays are data structures that allow the user to store a collection of data of the same type. Jul 29, 2022 · Hey guys, In this video, We're going to solve the Maximum Sum SubMatrix Problem using Kadane's Algorithm. Jul 23, 2025 · Given a matrix of size M x N, there are large number of queries to find submatrix sums. If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid. Mar 8, 2024 · Problem Formulation: We’re tackling the challenge of calculating the sum of values within a rectangular subarray (or submatrix) within a given 2D matrix such that the sum does not exceed a predefined value, k. The goal is to find the maximum sum of all possible square submatrices of a specified size within the matrix. The idea behind this algorithm is to fix the left and right columns and try to find the sum of the element from the left column to right column for each row, and store it temporarily. , a rectangular section of the matrix) that has the maximum possible sum among all possible submatrices. This problem is significant in various applications such as image processing, financial analysis, and any domain where analyzing sub-regions of a matrix is crucial. Mar 10, 2021 · Think of this as a simple 1D array, where you have to find the maximum contiguous subsequence sum (exactly what Kadane's Algorithm does). Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm Applications (Dynamic Programming) Back To Back SWE 251K subscribers Subscribe Given a 2D integer matrix A of size N x N find a B x B submatrix where B<= N and B>= 1, such that sum of all the elements in submatrix is maximum. org/submatrix-sum-queries/This video is contributed by Nideesh Terapalli. The problem is stated and solved here using Kadane's algorithm for a 2D matrix. Output: A submatrix of any size such that its summation is the maximum among all possible submatrices. Input: A 2-dimensional array NxN - Matrix - with positive and negative elements. May 4, 2015 · Maximum Sum Rectangular Submatrix in Matrix dynamic programming/2D kadane Tushar Roy - Coding Made Simple 249K subscribers Subscribed Can you solve this real interview question? Max Sum of Rectangle No Larger Than K - Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k. Similarly, the 2D array here also stores the prefix sum. The task is to find the maximum sum of any submatrix from the given matrix mat [] []. Nov 11, 2021 · Given a 2D matrix, find the largest possible sum submatrix in it and print its value. I want to find out an MxM submatrix, with largest sum of its elements, of the above matrix. Jul 31, 2023 · Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix’s upper-left Jan 13, 2024 · Photo by Margaret Jaszowska on Unsplash PROBLEM STATEMENT: Given a 2D matrix M of dimensions RxC. Return the maximum Understanding the Problem The core challenge of this problem is to identify the submatrix within a given m x n grid that has the maximum sum. Naive Approach: The simplest approach is to check for all possible submatrices from the given matrix whether the sum of its elements is at most K or not. Maximum Matrix Sum in Python, Java, C++ and more. This is a python code which implements a new algorithm to find the rectangular submatrix of maximum sum in a given M by N matrix, which is a common algorithm exercise. Two elements are considered adjacent if and only if they share a border. Examples: Input: K = 2, S = 14, mat Jul 22, 2025 · Given an integer array arr [], find the subarray (containing at least one element) which has the maximum possible sum, and return that sum. We can optimize it to O (N M) which is the best possible time complexity possible for any matrix. Obviously the time complexity will be very high: O (N^2 M^2). Here is your code with minimal changes: Apr 3, 2022 · Do Like Comment Share and Subscribe ️ ️📣 Day 7 : #goProWithBroCoders ️ Maximum Sum Square Sub-Matrix : https://www. ijivp dehauqy bekbv mupq pkdumswm eit muxyqry ihwp ttuq yob zgnbch eiui cxrbk swavb ntmrb