File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .ArrayDeque ;
2+ import java .util .Deque ;
3+
4+ /*
5+ * @lc app=leetcode.cn id=907 lang=java
6+ *
7+ * [907] 子数组的最小值之和
8+ */
9+
10+ // @lc code=start
11+ class Solution {
12+
13+ static int mod = 1000000007 ;
14+
15+ public int sumSubarrayMins (int [] arr ) {
16+
17+ int [] ls = new int [arr .length ];
18+ int [] rs = new int [arr .length ];
19+ Deque <Integer > ds = new ArrayDeque <Integer >();
20+
21+ for (int i = 0 ; i < arr .length ; i ++) {
22+ while (!ds .isEmpty () && arr [i ] <= arr [ds .peek ()]) {
23+ ds .pop ();
24+ }
25+
26+ ls [i ] = i - (!ds .isEmpty () ? ds .peek (): -1 );
27+ ds .push (i );
28+ }
29+
30+ ds .clear ();
31+ for (int i = arr .length - 1 ; i >= 0 ; i --) {
32+ while (!ds .isEmpty () && arr [i ] < arr [ds .peek ()]) {
33+ ds .pop ();
34+ }
35+ rs [i ] = (!ds .isEmpty () ? ds .peek () : arr .length ) - i ;
36+ ds .push (i );
37+ }
38+
39+ long result = 0 ;
40+
41+ for (int i = 0 ; i < rs .length ; i ++) {
42+ result += (long )ls [i ] * rs [i ] * arr [i ];
43+ result %= mod ;
44+ }
45+
46+ return (int ) result ;
47+ }
48+ }
49+ // @lc code=end
50+
You can’t perform that action at this time.
0 commit comments