-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP35.java
More file actions
52 lines (37 loc) · 1.28 KB
/
P35.java
File metadata and controls
52 lines (37 loc) · 1.28 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
package stack_and_queue;
// Sum of minimum and maximum elements of all sub arrays
import java.util.Deque;
import java.util.LinkedList;
public class P35 {
public static int sumOfSubArray(int[] arr, int k) {
int sum = 0;
Deque<Integer> s = new LinkedList<>();
Deque<Integer> g = new LinkedList<>();
int i = 0;
for(i = 0; i < k; i++) {
while(!s.isEmpty() && arr[s.peekLast()] >= arr[i])
s.removeLast();
while(!g.isEmpty() && arr[g.peekLast()] <= arr[i])
g.removeLast();
g.addLast(i);
s.addLast(i);
}
for(; i < arr.length; i++) {
sum += arr[s.peekFirst()] + arr[g.peekFirst()];
while(!s.isEmpty() && s.peekLast() <= i - k)
s.removeFirst();
while(!g.isEmpty() && g.peekFirst() <= i - k)
g.removeLast();
while(!s.isEmpty() && arr[s.peekLast()] >= arr[i])
s.removeLast();
while(!g.isEmpty() && arr[g.peekLast()] <= arr[i])
g.removeLast();
g.addLast(i);
s.addLast(i);
}
sum += arr[s.peekFirst()] + arr[g.peekFirst()];
return sum;
}
public static void main(String[] args) {
}
}