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

Commitef3c0f2

Browse files
author
applewjg
committed
LargestRectangleinHistogram
Change-Id: I2bf540dbfa158c9292cb7fdbe4f3c356d36fb1c7
1 parent48db8be commitef3c0f2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎LargestRectangleinHistogram.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 6, 2015
4+
Problem: Largest Rectangle in Histogram
5+
Difficulty: Hard
6+
Source: https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
7+
Notes:
8+
Given n non-negative integers representing the histogram's bar height where the width of each
9+
bar is 1, find the area of largest rectangle in the histogram.
10+
For example,
11+
Given height = [2,1,5,6,2,3],
12+
return 10.
13+
14+
Solution: 1. Only calucate area when reaching local maximum value.
15+
2. Keep a non-descending stack. O(n). if the vector height is not allowed to be changed.
16+
*/
17+
publicclassSolution {
18+
publicintlargestRectangleArea_1(int[]height) {
19+
intres =0;
20+
for (inti =0;i <height.length; ++i) {
21+
if ((i <height.length -1) && (height[i] <=height[i+1])) {
22+
continue;
23+
}
24+
intminheight =height[i];
25+
for (intj =i;j >=0; --j) {
26+
minheight =Math.min(minheight,height[j]);
27+
res =Math.max(res, (i-j+1)*minheight);
28+
}
29+
}
30+
returnres;
31+
}
32+
publicintlargestRectangleArea(int[]height) {
33+
intres =0;
34+
Stack<Integer>stk =newStack<Integer>();
35+
inti =0;
36+
while (i <height.length) {
37+
if (stk.isEmpty() ==true || (height[i] >=height[stk.peek()])) {
38+
stk.push(i++);
39+
}else {
40+
intidx =stk.pop();
41+
intwidth =stk.isEmpty() ?i : (i -stk.peek() -1);
42+
res =Math.max(res,width*height[idx]);
43+
}
44+
}
45+
while (stk.isEmpty() ==false) {
46+
intidx =stk.pop();
47+
intwidth =stk.isEmpty() ?height.length : (height.length -stk.peek() -1);
48+
res =Math.max(res,width*height[idx]);
49+
}
50+
returnres;
51+
}
52+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp