This link shares a nice solution with explanation using DP. You'll be a clear of the algorithm after running it in its suggested example:
Matrix = [[0,0,0,1,0,0,0],[0,0,1,1,1,0,0],[0,1,1,1,1,1,0]];
The code is rewritten as follows.
1 classSolution {2 Public:3 intMaximalrectangle (vector<vector<Char>>&matrix) {4 if(Matrix.empty ())return 0;5 Const intm = Matrix.size (), n = matrix[0].size ();6 int*left =New intN (), *right =New intN (), *height =New int[n] ();7 Fill_n (right, n, N);8 intArea =0;9 for(inti =0; I < m; i++) {Ten intL =0, r =N; One for(intj =0; J < N; J + +) AHEIGHT[J] + = matrix[i][j] = ='1'?1: -Height[j]; - for(intj =0; J < N; J + +) { - if(Matrix[i][j] = ='1') Left[j] =Max (Left[j], L); the ElseLEFT[J] =0, L = j +1; - } - for(intj = N-1; J >=0; j--) { - if(Matrix[i][j] = ='1') Right[j] =min (right[j], R); + ElseRight[j] = N, r =J; - } + for(intj =0; J < N; J + +) AArea = max (area, (Right[j]-left[j]) *height[j]); at } - returnArea ; - } -};
[Leetcode] Maximal Rectangle