-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathSpecialProduct.java
70 lines (56 loc) · 1.53 KB
/
SpecialProduct.java
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
package Array;
import java.util.ArrayList;
import java.util.Stack;
/**
* Author - archit.s
* Date - 01/09/18
* Time - 6:23 PM
*/
public class SpecialProduct {
private ArrayList<Integer> leftSpecialV(ArrayList<Integer> A){
ArrayList<Integer> r = new ArrayList<>();
Stack<Integer> s = new Stack<>();
for(int i=0;i<A.size();i++){
while(!s.empty() && A.get(s.peek()) <= A.get(i)){
s.pop();
}
if(s.empty()){
r.add(0);
}
else{
r.add(s.peek());
}
s.push(i);
}
return r;
}
private ArrayList<Integer> rightSpecialV(ArrayList<Integer> A){
ArrayList<Integer> r = new ArrayList<>();
Stack<Integer> s = new Stack<>();
for(int i=A.size()-1;i>=0;i--){
while(!s.empty() && A.get(s.peek()) <= A.get(i)){
s.pop();
}
if(s.empty()){
r.add(0,0);
}
else{
r.add(0,s.peek());
}
s.push(i);
}
return r;
}
public int maxSpecialProduct(ArrayList<Integer> A) {
ArrayList<Integer> l = leftSpecialV(A);
ArrayList<Integer> r = rightSpecialV(A);
long product=0, res= 0;
for(int i=0;i<A.size();i++){
res= (long)l.get(i) * (long)r.get(i);
if(product < res){
product = res;
}
}
return (int)(product%1000000007);
}
}