Maximum Consistent Columns in a Grid Problem
Description
LeetCode Problem 3989.
You are given a 2D integer array grid of size m x n, and an integer limit.
You may remove zero or more columns from the grid, but at least one column must remain. The relative order of the remaining columns must be preserved.
A grid is called consistent if for every row i, and for every pair of adjacent remaining columns a and b with a < b, the following holds: |grid[i][b] - grid[i][a]| <= limit.
Return the maximum number of columns that can remain such that the resulting grid is consistent.
Example 1:
Input: grid = [[-2,0,3]], limit = 2
Output: 2
Explanation:
- Remove column 2 and keep columns 0 and 1, which gives |grid[0][1] − grid[0][0]| = |0 − (−2)| = 2 <= limit.
- Thus, the maximum number of columns that can remain is 2.
Example 2:
Input: grid = [[1,-1,1],[2,2,2]], limit = 1
Output: 2
Explanation:
- Remove column 1 and keep columns 0 and 2, which gives
- |grid[0][2] − grid[0][0]| = |1 − 1| = 0 <= limit and
- |grid[1][2] − grid[1][0]| = |2 − 2| = 0 <= limit.
- Thus, the maximum number of columns that can remain is 2.
Example 3:
Input: grid = [[-5,5]], limit = 9
Output: 1
Explanation:
- Remove either column 0 or column 1, since |grid[0][1] − grid[0][0]| = |5 − (−5)| = 10 > limit.
- Thus, the maximum number of columns that can remain is 1.
Constraints:
1 <= m == grid.length <= 2501 <= n == grid[i].length <= 250-10^5 <= grid[i][j] <= 10^50 <= limit <= 10^5
Solution
Approach: Longest chain of compatible columns
Two columns a < b can sit next to each other when |grid[i][b] - grid[i][a]| <= limit holds in every row. A consistent grid is exactly a sequence of columns in increasing order where each neighbouring pair is compatible, so we want the longest such chain.
Let dp[b] be the longest chain that ends at column b. Then dp[b] = 1 + max(dp[a]) over all earlier columns a compatible with b (or just 1 if there is none). Checking a pair costs O(m), so the whole table costs O(n^2 * m), which is about 16 million steps for 250 x 250. The answer is the largest dp value. Skipping the check when dp[a] + 1 cannot improve dp[b] saves much of the work.
Complexity: time O(n^2 * m), space O(n).
class Solution:
def maxConsistentColumns(self, grid: List[List[int]], limit: int) -> int:
cols = list(zip(*grid))
n = len(cols)
dp = [1] * n
for b in range(n):
for a in range(b):
if dp[a] + 1 > dp[b] and all(abs(x - y) <= limit for x, y in zip(cols[a], cols[b])):
dp[b] = dp[a] + 1
return max(dp)