Similar Problems

Similar Problems not available

Largest Submatrix With Rearrangements - Leetcode Solution


LeetCode:  Largest Submatrix With Rearrangements Leetcode Solution

Difficulty: Medium

Topics: greedy matrix sorting array  

Problem Statement:

Given a matrix of integers A with R rows and C columns, find the maximum score of a matrix where each entry is a non-negative integer and the sum of the row and column of that entry doesn't exceed k.

In other words, the objective is to choose the largest possible square submatrix from the given matrix such that the sum of row and column indices for each element in the submatrix is less than or equal to k. The score of the matrix is the sum of all its elements.


The first step is to realize that the constraints of the problem (sum of row and column indices) can be used to our advantage. Since the key is to find the largest possible submatrix, we can start by assuming that the submatrix will be square.

The next step is to sort each row in increasing order and each column in decreasing order. This ensures that elements with the highest value are placed in the top left corner of the matrix and can be included in the submatrix. This is because the sum of row and column indices is maximum in the top left corner. Therefore, by placing the largest elements in the top left corner, we can include the maximum number of elements in the submatrix.

After sorting the rows and columns, we can iterate over each cell in the matrix and compute the value of the highest possible submatrix that includes that cell. We can do this by considering all possible submatrices that use that cell as the top left corner and have each row and column index sum less than or equal to k. We can use dynamic programming to solve this problem efficiently.

Let dp[i][j] represent the maximum possible value of a submatrix that can be formed using the cell (i,j) as the top left corner. We can initialize dp[i][j] = A[i][j], since the submatrix that only contains the cell (i,j) has a maximum value of A[i][j].

To compute the value of dp[i][j] for other submatrices, we can use the following recurrence:

dp[i][j] = A[i][j] + max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])

This recurrence takes into account the constraints on row and column indices while computing the maximum value of the submatrix. We can compute dp[i][j] for all cells in the matrix and take the maximum value as the answer to the problem.

Time Complexity: Sorting the rows and columns takes O(RlogC + ClogR) time. Computing the values of dp[][] takes O(RC) time. Therefore, the overall time complexity of the solution is O(RlogC + ClogR + RC).

Space Complexity: We use a 2D array of size R x C to store the values of dp[i][j]. Therefore, the space complexity of the solution is O(RC).

Largest Submatrix With Rearrangements Solution Code