- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 68 lines of C++ from the credited upstream file maximum-consistent-columns-in-a-grid.cpp.
- The implementation visibly relies on sequence storage, ordered lookup, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int maxConsistentColumns(vector<vector<int>>& grid, int limit) {8 static const int N = 250;9 10 vector<bitset<N>> lookup(size(grid[0]));11 for (auto& x : lookup) {12 x.set();13 }14 for (int i = 0; i < size(grid); ++i) {15 vector<int> idxs(size(grid[0]));16 iota(begin(idxs), end(idxs), 0);17 sort(begin(idxs), end(idxs), [&](const auto& a, const auto& b){18 return grid[i][a] < grid[i][b];19 });20 vector<int> arr(size(grid[0]));21 for (int j = 0; j < size(grid[0]); ++j) {22 arr[j] = grid[i][idxs[j]];23 }24 vector<bitset<N>> prefix(size(grid[0]) + 1);25 for (int j = 0; j < size(grid[0]); ++j) {26 prefix[j + 1] = prefix[j];27 prefix[j + 1][idxs[j]] = 1;28 }29 for (int j = 0; j < size(grid[0]); ++j) {30 lookup[j] &= prefix[distance(begin(arr), upper_bound(begin(arr), end(arr), grid[i][j] + limit))]31 ^ prefix[distance(begin(arr), lower_bound(begin(arr), end(arr), grid[i][j] - limit))];32 }33 }34 vector<int> dp(size(grid[0]));35 for (int j = 0; j < size(grid[0]); ++j) {36 int mx = 0;37 for (int k = lookup[j]._Find_first(); k < j; k = lookup[j]._Find_next(k)) {38 mx = max(mx, dp[k]);39 }40 dp[j] = mx + 1;41 }42 return ranges::max(dp);43 }44};45 46474849class Solution2 {50public:51 int maxConsistentColumns(vector<vector<int>>& grid, int limit) {52 vector<int> dp(size(grid[0]), 1);53 for (int i = 0; i < size(grid[0]); ++i) {54 for (int j = 0; j < i; ++j) {55 if (dp[j] + 1 <= dp[i]) {56 continue;57 }58 if (all_of(cbegin(grid), cend(grid), [&](const auto& row) {59 return abs(row[i] - row[j]) <= limit;60 })) {61 dp[i] = dp[j] + 1;62 }63 }64 }65 return ranges::max(dp);66 }67};68