Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cdd9b3d

Browse files
committedMar 23, 2025
Add solution #907
1 parent 7b1300a commit cdd9b3d

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

Diff for: ‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,7 @@
717717
904|[Fruit Into Baskets](./0904-fruit-into-baskets.js)|Medium|
718718
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
719719
906|[Super Palindromes](./0906-super-palindromes.js)|Hard|
720+
907|[Sum of Subarray Minimums](./0907-sum-of-subarray-minimums.js)|Medium|
720721
909|[Snakes and Ladders](./0909-snakes-and-ladders.js)|Medium|
721722
912|[Sort an Array](./0912-sort-an-array.js)|Medium|
722723
914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|

Diff for: ‎solutions/0907-sum-of-subarray-minimums.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 907. Sum of Subarray Minimums
3+
* https://leetcode.com/problems/sum-of-subarray-minimums/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous)
7+
* subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
8+
*/
9+
10+
/**
11+
* @param {number[]} arr
12+
* @return {number}
13+
*/
14+
var sumSubarrayMins = function(arr) {
15+
const MOD = 1e9 + 7;
16+
const left = new Array(arr.length);
17+
const right = new Array(arr.length);
18+
const stack = [];
19+
20+
for (let i = 0; i < arr.length; i++) {
21+
while (stack.length && arr[stack[stack.length - 1]] > arr[i]) {
22+
stack.pop();
23+
}
24+
left[i] = stack.length ? i - stack[stack.length - 1] : i + 1;
25+
stack.push(i);
26+
}
27+
28+
stack.length = 0;
29+
for (let i = arr.length - 1; i >= 0; i--) {
30+
while (stack.length && arr[stack[stack.length - 1]] >= arr[i]) {
31+
stack.pop();
32+
}
33+
right[i] = stack.length ? stack[stack.length - 1] - i : arr.length - i;
34+
stack.push(i);
35+
}
36+
37+
let result = 0;
38+
for (let i = 0; i < arr.length; i++) {
39+
result = (result + arr[i] * left[i] * right[i]) % MOD;
40+
}
41+
42+
return result;
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.