Created
March 20, 2025 17:07
-
-
Save Tribhuwan-Joshi/cc696d8fd872a9dcf8c59cbe44970420 to your computer and use it in GitHub Desktop.
Biggest black square algorithmic question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <stack> | |
#include <algorithm> | |
#include <iostream> | |
using namespace std; | |
class Solution { | |
public: | |
int solution(vector<int>& A) { | |
int N = A.size(); | |
int maxSide = 0; | |
for (int r = 0; r < N; r++) { | |
vector<int> heights(N); | |
for (int c = 0; c < N; c++) { | |
heights[c] = (A[c] >= N - r) ? N - r : 0; | |
} | |
maxSide = max(maxSide, biggestSquare(heights)); | |
} | |
return maxSide; | |
} | |
private: | |
int biggestSquare(vector<int>& heights) { | |
stack<int> stk; | |
int maxSide = 0; | |
int N = heights.size(); | |
for (int i = 0; i <= N; i++) { | |
int h = (i == N) ? 0 : heights[i]; | |
while (!stk.empty() && heights[stk.top()] > h) { | |
int height = heights[stk.top()]; | |
stk.pop(); | |
int width = stk.empty() ? i : i - stk.top() - 1; | |
maxSide = max(maxSide, min(height, width)); | |
} | |
stk.push(i); | |
} | |
return maxSide; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment