File tree 2 files changed +64
-0
lines changed
2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+ public int largestRectangleArea (int [] height ) {
3
+ if (height .length == 0 ){
4
+ return 0 ;
5
+ }
6
+ Stack <Integer > stack = new Stack <Integer >();//record the index of block
7
+ int max = 0 ;
8
+ for (int i = 0 ; i <= height .length ; i ++){
9
+ int curr = (i == height .length ) ? -1 : height [i ];
10
+ while (!stack .isEmpty () && curr <= height [stack .peek ()]){
11
+ int h = height [stack .pop ()];
12
+ int w = stack .isEmpty ()? i : i - stack .peek () - 1 ;
13
+ max = Math .max (max , h * w );
14
+ }
15
+ stack .push (i );
16
+ }
17
+ return max ;
18
+ }
19
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .Stack ;
2
+
3
+ //Min_stack
4
+ // using two stacks to implement a minstack
5
+ // the first stack is to store numbers, the other one is to store the min number from 1st stack
6
+
7
+ public class minstack {
8
+ private Stack <Integer > stack1 ;
9
+ private Stack <Integer > min_stack ;
10
+ // copy constructor
11
+ public minstack (){
12
+ stack1 = new Stack <Integer >();
13
+ min_stack = new Stack <Integer >();
14
+ }
15
+
16
+ public void push (int number ){
17
+ stack1 .push (number );
18
+ if (min_stack .empty ()){
19
+ min_stack .push (number );
20
+ }else {
21
+ if (min_stack .peek () >= number ){
22
+ min_stack .push (number );
23
+ }
24
+ }
25
+ }
26
+ public int pop (){
27
+ if (stack1 .peek () == min_stack .peek ()){
28
+ min_stack .pop ();
29
+ }
30
+ return stack1 .pop ();
31
+ }
32
+ public int min (){
33
+ return min_stack .peek ();
34
+ }
35
+ public static void main (String [] args ){
36
+ minstack minstack = new minstack ();
37
+ minstack .push (2 );
38
+ minstack .push (4 );
39
+ minstack .push (10 );
40
+ minstack .push (3 );
41
+ minstack .pop ();
42
+ System .out .println (minstack .min ());
43
+ }
44
+ }
45
+
You can’t perform that action at this time.
0 commit comments