Skip to content

Commit a415a95

Browse files
ankana2113pre-commit-ci[bot]MaximSmolskiy
authored
Add largest rectangle histogram (#12269)
* added ridge regression * added ridge regression * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * added ridge regression * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ridge regression * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * resolved errors * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * resolved conflicts * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * added doctests * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ruff and minor checks * minor chenges * minor checks * minor checks * minor changes * descriptive names * Fix ruff check in loss_functions.py * fixed pre-commit issues * added largest rectangle histogram function * added largest rectangle histogram function * Update frequent_pattern_growth.py * Update loss_functions.py * Delete machine_learning/ridge_regression/__init__.py * Delete machine_learning/ridge_regression/ADRvsRating.csv * Delete machine_learning/ridge_regression/ridge_regression.py * Delete machine_learning/ridge_regression/test_ridge_regression.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maxim Smolskiy <[email protected]>
1 parent fff34ed commit a415a95

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def largest_rectangle_area(heights: list[int]) -> int:
2+
"""
3+
Inputs an array of integers representing the heights of bars,
4+
and returns the area of the largest rectangle that can be formed
5+
6+
>>> largest_rectangle_area([2, 1, 5, 6, 2, 3])
7+
10
8+
9+
>>> largest_rectangle_area([2, 4])
10+
4
11+
12+
>>> largest_rectangle_area([6, 2, 5, 4, 5, 1, 6])
13+
12
14+
15+
>>> largest_rectangle_area([1])
16+
1
17+
"""
18+
stack: list[int] = []
19+
max_area = 0
20+
heights = [*heights, 0] # make a new list by appending the sentinel 0
21+
n = len(heights)
22+
23+
for i in range(n):
24+
# make sure the stack remains in increasing order
25+
while stack and heights[i] < heights[stack[-1]]:
26+
h = heights[stack.pop()] # height of the bar
27+
# if stack is empty, it means entire width can be taken from index 0 to i-1
28+
w = i if not stack else i - stack[-1] - 1 # calculate width
29+
max_area = max(max_area, h * w)
30+
31+
stack.append(i)
32+
33+
return max_area
34+
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)