LC 85 - Maximal Rectangle

Approach Today’s daily can be solved with the technique as mono-stack in LC-84. First, we calculate the continuous 1 in the horizontal direction (only need to calculate one side). For instance, given 0 1 1 0 0 1 1 1 we have 0 1 2 0 0 1 2 3 denoting how many ones are there, and then we process each vertical direction as it is a histogram (as LC-84). ...

January 11, 2026 · 2 min

LC 84 - Largest Rectangle in Histogram

Approach For each value in the vector, we need to find the first one that is smaller than it in the left (and right), and this can be done with mono-stack. So we maintain a mono-stack and record the first index smaller than it on the left (and right) hand side, and in the end right-left-1 times the current value is the maximum profit for this position. Code class Solution { public: int largestRectangleArea(vector<int>& heights) { heights.insert(heights.begin(), INT_MIN); heights.insert(heights.end(), INT_MIN); int n = heights.size(); vector<int> left(n, -1); vector<int> right(n, -1); { stack<int> stk; stk.push(0); for(int i = 1 ; i < n-1 ; ++i) { while(!stk.empty()) { int prevIdx = stk.top(); if(heights[prevIdx] >= heights[i]) { stk.pop(); } else { left[i] = prevIdx; stk.push(i); break; } } } } { stack<int> stk; stk.push(n-1); for(int i = n-2 ; i >= 0 ; --i) { while(!stk.empty()) { int prevIdx = stk.top(); if(heights[prevIdx] >= heights[i]) { stk.pop(); } else { right[i] = prevIdx; stk.push(i); break; } } } } // calculate int prof = INT_MIN; for(int i = 1 ; i < n-1 ; ++i) { prof = max(prof, (right[i]-left[i]-1)*heights[i]); } return prof; } };

January 10, 2026 · 1 min

LC 42 - Trapping Rain Water

Approach I was orginally thinking that we can colelct all the peaks, and fill the water between peaks, but finding that this might not be correct. For example like [2,0,1,0,1,0,2], if we fill between peaks, the 3-rd (0-indexed) would be 1, but it is actaully 2. Later I come up with the idea for using mono stack. We collect all the points in increasing order, and try to fill from one to another. We also do the same thing backwards, since the mono-stack would stop on the largest element. ...

January 8, 2026 · 2 min