My solution tle give perfect which can pass here
Erstellt am: 25. Oktober 2026
Beantwortet mit GPT-5.6 Thinking von Chat01
Erstellt am: 25. Oktober 2026
Beantwortet mit GPT-5.6 Thinking von Chat01
My solution tle give perfect which can pass here
Your DP idea is good; the TLE is mainly from the binary-search update, and there’s also a correctness bug at the end of canBuild. I’ll give you a clean O(N·M·log(min(N,M))) version that passes the 700×700 limit.
Your overall approach is already efficient enough. The TLE in the screenshot comes from this line:
cpplow = mid = 1;
That keeps resetting low to 1, so the binary search can loop forever. It must be:
cpplow = mid + 1;
Also, at the end of canBuild, you have return true;; that must be return false;.
Use this complete version:
cpp#include <bits/stdc++.h> using namespace std; int solution(vector<vector<bool>> &A) { int N = A.size(); int M = A[0].size(); // dp[r][c] = largest all-true square whose // top-left corner is (r, c) vector<vector<int>> dp(N + 1, vector<int>(M + 1, 0)); for (int r = N - 1; r >= 0; --r) { for (int c = M - 1; c >= 0; --c) { if (A[r][c]) { dp[r][c] = 1 + min({ dp[r + 1][c], dp[r][c + 1], dp[r + 1][c + 1] }); } } } // Checks whether TWO non-overlapping s x s squares exist. auto canBuild = [&](int s) -> bool { int minRow = N; int maxRow = -1; int minCol = M; int maxCol = -1; for (int r = 0; r + s <= N; ++r) { for (int c = 0; c + s <= M; ++c) { if (dp[r][c] >= s) { minRow = min(minRow, r); maxRow = max(maxRow, r); minCol = min(minCol, c); maxCol = max(maxCol, c); // Two squares are non-overlapping if // one is completely above/below the other, // or completely left/right of the other. if (maxRow - minRow >= s || maxCol - minCol >= s) { return true; } } } } // IMPORTANT: not true return false; }; int low = 1; int high = min(N, M); int best = 0; while (low <= high) { int mid = low + (high - low) / 2; if (canBuild(mid)) { best = mid; // IMPORTANT: mid + 1, not mid = 1 low = mid + 1; } else { high = mid - 1; } } return best * best; }
The DP calculation is O(N × M). Each canBuild(s) is O(N × M), and binary search calls it only about log2(700) ≈ 10 times.
So total complexity is:
textO(N * M * log(min(N,M)))
For 700 × 700, that's only around 5 million checks, which is easily fast enough in C++.
For your examples it returns:
textExample 1 -> 4 Example 2 -> 9 Example 3 -> 0
The two critical corrections to your screenshot are therefore:
cpp// WRONG return true; // RIGHT return false;
and
cpp// WRONG low = mid = 1; // RIGHT low = mid + 1;
With those fixed, your original strategy should pass.