-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDanDiaoStackEqual.java
More file actions
94 lines (79 loc) · 2.07 KB
/
DanDiaoStackEqual.java
File metadata and controls
94 lines (79 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.*;
public class DanDiaoStackEqual{
private Stack<LinkedList<Integer>> stack;
private int[] arr;
public DanDiaoStackEqual(int[] _arr){
arr = _arr;
stack = new Stack<LinkedList<Integer>>();
}
public int[][] getResult(){
int[][] result = new int[arr.length][2];
boolean isNotEqual=true;
for (int i=0; i<arr.length;i++ ) {
LinkedList<Integer> list = new LinkedList<Integer>();
isNotEqual=true;
if(stack.isEmpty()){
list.offerLast(i);
stack.push(list);
}else{
while(!stack.isEmpty()){
LinkedList<Integer> curList = stack.peek();
int curIndex = curList.peekLast();
if(arr[curIndex] == arr[i]){
curList.offerLast(i);
isNotEqual=false;
break;
}else if(arr[curIndex] < arr[i]){
break;
}else{
curList = stack.pop();
for (int cur : curList ) {
result[cur][0] = stack.isEmpty()?-1:stack.peek().peekLast();
result[cur][1] = i;
}
}
}
if(isNotEqual){
list.offerLast(i);
stack.push(list);
}
}
}
while(!stack.isEmpty()){
LinkedList<Integer> curList = stack.pop();
for (int cur : curList ) {
result[cur][0] = stack.isEmpty()?-1:stack.peek().peekLast();
result[cur][1] = -1;
}
}
return result;
}
public static void main(String[] args){
int[] arr= new int[]{3,5,1,4,2,3,7,5,2,4,5,2,0};
DanDiaoStackEqual dan=new DanDiaoStackEqual(arr);
int[][] result = dan.getResult();
for (int i=0; i<result.length;i++ ) {
for (int j=0; j<result[i].length; j++) {
System.out.print(result[i][j]+",");
}
System.out.println();
}
int max = 0;
int index = 0;
int start = 0;
int end = 0;
for (int i=0; i<arr.length;i++ ) {
int L = result[i][0] == -1 ? 0:result[i][0]+1;
int R = result[i][1] == -1 ? arr.length:result[i][1];
if(arr[i]*(R-L) > max){
max = arr[i]*(R-L);
index = i;
start = L;
end = R;
}
System.out.println("max ="+max+"; index = "+i+"(R-L) = "+(R-L));
}
System.out.println("max ="+max+"; index = "+index);
System.out.println("range=["+(start)+","+(end-1)+"]");
}
}