Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit354dbbd

Browse files
authored
Create 84. Largest Rectangle in Histogram
Runtime: 269 ms, faster than 23.53% of C online submissions for Largest Rectangle in Histogram.Memory Usage: 20.3 MB, less than 8.82% of C online submissions for Largest Rectangle in Histogram.
1 parentfb55f39 commit354dbbd

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

‎c/84. Largest Rectangle in Histogram

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp