From d5639d4e1a912eebc926762dc143593db85106d6 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 4 Sep 2017 10:35:14 +0800 Subject: [PATCH] Largest rectangle in histogram Signed-off-by: begeekmyfriend --- 084_largest_rectangle_in_histogram/Makefile | 2 ++ .../rect_in_histogram.c | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 084_largest_rectangle_in_histogram/Makefile create mode 100644 084_largest_rectangle_in_histogram/rect_in_histogram.c diff --git a/084_largest_rectangle_in_histogram/Makefile b/084_largest_rectangle_in_histogram/Makefile new file mode 100644 index 0000000..8306292 --- /dev/null +++ b/084_largest_rectangle_in_histogram/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test rect_in_histogram.c diff --git a/084_largest_rectangle_in_histogram/rect_in_histogram.c b/084_largest_rectangle_in_histogram/rect_in_histogram.c new file mode 100644 index 0000000..7036579 --- /dev/null +++ b/084_largest_rectangle_in_histogram/rect_in_histogram.c @@ -0,0 +1,31 @@ +#include +#include + +static int largestRectangleArea(int* heights, int heightsSize) +{ + int i, max_area = 0; + for (i = 0; i < heightsSize; i++) { + if (i > 0 && heights[i - 1] == heights[i]) { + continue; + } + int low = i; + int high = i; + while (low - 1 >= 0 && heights[low - 1] >= heights[i]) { + low--; + } + while (high + 1 < heightsSize && heights[high + 1] >= heights[i]) { + high++; + } + int area = (high - low + 1) * heights[i]; + max_area = area > max_area ? area : max_area; + } + return max_area; +} + +int main(void) +{ + int nums[] = { 2, 1, 5, 6, 2, 3 }; + int count = sizeof(nums) / sizeof(*nums); + printf("%d\n", largestRectangleArea(nums, count)); + return 0; +}