|
| 1 | +const int MAX_N = 1e5 + 5; |
| 2 | +struct Stack |
| 3 | +{ |
| 4 | +int top; |
| 5 | +int capacity; |
| 6 | +int *array; |
| 7 | +}; |
| 8 | + |
| 9 | +struct Stack *createStack() |
| 10 | +{ |
| 11 | +struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack)); |
| 12 | +stack->capacity = MAX_N; |
| 13 | +stack->top = -1; |
| 14 | +stack->array = (int *)malloc(stack->capacity * sizeof(int)); |
| 15 | +return stack; |
| 16 | +} |
| 17 | + |
| 18 | +int isFull(struct Stack *stack) |
| 19 | +{ |
| 20 | +return stack->top == stack->capacity - 1; |
| 21 | +} |
| 22 | + |
| 23 | +int isEmpty(struct Stack *stack) |
| 24 | +{ |
| 25 | +return stack->top == -1; |
| 26 | +} |
| 27 | + |
| 28 | +void push(struct Stack *stack, int val) |
| 29 | +{ |
| 30 | +if (isFull(stack)) |
| 31 | +return; |
| 32 | +stack->array[++stack->top] = val; |
| 33 | +} |
| 34 | + |
| 35 | +void pop(struct Stack *stack) |
| 36 | +{ |
| 37 | +if (isEmpty(stack)) |
| 38 | +return; |
| 39 | +--stack->top; |
| 40 | +} |
| 41 | + |
| 42 | +int peek(struct Stack *stack) |
| 43 | +{ |
| 44 | +if (isEmpty(stack)) |
| 45 | +return INT_MIN; |
| 46 | +return stack->array[stack->top]; |
| 47 | +} |
| 48 | + |
| 49 | +int max(int num1, int num2) |
| 50 | +{ |
| 51 | +return (num1 > num2) ? num1 : num2; |
| 52 | +} |
| 53 | + |
| 54 | +int largestRectangleArea(int *heights, int heightsSize) |
| 55 | +{ |
| 56 | +int ans = 0; |
| 57 | +struct Stack *st = createStack(); |
| 58 | +for (int i = 0; i < heightsSize; i++) |
| 59 | +{ |
| 60 | +while (!isEmpty(st) && heights[peek(st)] > heights[i]) |
| 61 | +{ |
| 62 | +int tp = peek(st); |
| 63 | +pop(st); |
| 64 | +int dist = (isEmpty(st) ? i : i - peek(st) - 1); |
| 65 | +ans = max(ans, dist * heights[tp]); |
| 66 | +} |
| 67 | +push(st, i); |
| 68 | +} |
| 69 | +while (!isEmpty(st)) |
| 70 | +{ |
| 71 | +int tp = peek(st); |
| 72 | +pop(st); |
| 73 | +int dist = (isEmpty(st) ? heightsSize : heightsSize - peek(st) - 1); |
| 74 | +ans = max(ans, dist * heights[tp]); |
| 75 | +} |
| 76 | +return ans; |
| 77 | +} |