Largest Rectangle

  • + 0 comments

    C#

    public static long largestRectangle(List<int> h) => 
            GetMaxArea(h, 0, h.Count()-1);
        
        private static long GetMaxArea(List<int> h, int l, int r) {
            if (l > r) return 0;
            if (l == r) return h[l];
            int min = int.MaxValue;
            int minIndex = -1;
            for (int i = l; i <= r; i++) {
                if (h[i] < min) {
                    min = h[i];
                    minIndex = i;
                }
            }
            long area = (r - l + 1) * min;
            long leftArea = GetMaxArea(h, l, minIndex-1);
            long rightArea = GetMaxArea(h, minIndex+1, r);
            return Math.Max(area, Math.Max(leftArea, rightArea));
        }