-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path907.java
55 lines (50 loc) · 1.66 KB
/
907.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
__________________________________________________________________________________________________
sample 5 ms submission
class Solution {
public int sumSubarrayMins(int[] A) {
int res = 0;
int mod = (int)1e9 + 7;
int j, k, top = -1;
int[] stack = new int[A.length];
for (int i = 0; i <= A.length; i++) {
while(top != -1 && A[stack[top]] > ((i == A.length) ? 0 : A[i])) {
j = stack[top--];
k = top == -1 ? -1 : stack[top];
res = (res + A[j] * (j - k) * (i - j)) % mod;
}
stack[++top] = i;
}
return res;
}
}
__________________________________________________________________________________________________
sample 40996 kb submission
class Solution {
public int sumSubarrayMins(int[] A) {
int MOD = 1_000_000_007;
Stack<RepInteger> stack = new Stack();
int ans = 0, dot = 0;
for (int j = 0; j < A.length; ++j) {
// Add all answers for subarrays [i, j], i <= j
int count = 1;
while (!stack.isEmpty() && stack.peek().val >= A[j]) {
RepInteger node = stack.pop();
count += node.count;
dot -= node.val * node.count;
}
stack.push(new RepInteger(A[j], count));
dot += A[j] * count;
ans += dot;
ans %= MOD;
}
return ans;
}
}
class RepInteger {
int val, count;
RepInteger(int v, int c) {
val = v;
count = c;
}
}
__________________________________________________________________________________________________