-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0907-sum-of-subarray-minimums.js
More file actions
75 lines (66 loc) · 2.04 KB
/
0907-sum-of-subarray-minimums.js
File metadata and controls
75 lines (66 loc) · 2.04 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
/**
* Sum Of Subarray Minimums
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
var sumSubarrayMins = function (arr) {
const modulusBase = 1_000_000_007;
const arrayLength = arr.length;
const leftBounds = new Array(arrayLength);
const rightBounds = new Array(arrayLength);
const monotonicStackForLeft = [];
for (
let currentLeftIndex = 0;
currentLeftIndex < arrayLength;
currentLeftIndex++
) {
while (
monotonicStackForLeft.length > 0 &&
arr[monotonicStackForLeft[monotonicStackForLeft.length - 1]] >
arr[currentLeftIndex]
) {
monotonicStackForLeft.pop();
}
const previousSmallerIndex =
monotonicStackForLeft.length > 0
? monotonicStackForLeft[monotonicStackForLeft.length - 1]
: -1;
leftBounds[currentLeftIndex] = currentLeftIndex - previousSmallerIndex;
monotonicStackForLeft.push(currentLeftIndex);
}
const monotonicStackForRight = [];
for (
let currentRightIndex = arrayLength - 1;
currentRightIndex >= 0;
currentRightIndex--
) {
while (
monotonicStackForRight.length > 0 &&
arr[monotonicStackForRight[monotonicStackForRight.length - 1]] >=
arr[currentRightIndex]
) {
monotonicStackForRight.pop();
}
const nextSmallerOrEqualIndex =
monotonicStackForRight.length > 0
? monotonicStackForRight[monotonicStackForRight.length - 1]
: arrayLength;
rightBounds[currentRightIndex] =
nextSmallerOrEqualIndex - currentRightIndex;
monotonicStackForRight.push(currentRightIndex);
}
let overallSum = 0;
for (
let finalCalculationIndex = 0;
finalCalculationIndex < arrayLength;
finalCalculationIndex++
) {
const elementValue = arr[finalCalculationIndex];
const rangeLeft = leftBounds[finalCalculationIndex];
const rangeRight = rightBounds[finalCalculationIndex];
const currentContribution =
(elementValue * rangeLeft * rangeRight) % modulusBase;
overallSum = (overallSum + currentContribution) % modulusBase;
}
return overallSum;
};