287. Find the Duplicate Number!

class Solution {
    public int largestRectangleArea(int[] heights) {
        // Key: use stack to store the index that are larget than the top one
        // calsue the max rectangle for each height
        int max = 0;
        
        // stores the index not the value
        Deque<Integer> memo = new LinkedList<>();
        for(int i=0; i<=heights.length; i++){
            int modifiedH= i==heights.length? 0 : heights[i];
            // remember: not heights[memo.peek()]>=modifiedH
            // if there is sequentials same height elements,
            // the correct value will be calcuated with pop out the first element
            while(memo.size()>0 && heights[memo.peek()]>modifiedH){
                int height = heights[memo.pop()];
                // contains left and right
                int left = memo.size() >0 ? memo.peek() + 1 : 0;
                int right = i-1;
                max=Math.max(max, height*(right-left+1));
            }
            memo.push(i);
        }
        return max;
    }
}

Last updated