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
| func sumSubarrayMins(arr []int) int { n := len(arr) leftArr := make([]int, n) queue := []int{} for i, num := range arr { for len(queue) > 0 && arr[queue[len(queue) - 1]] > num { queue = queue[:len(queue) - 1] } if len(queue) == 0 { leftArr[i] = -1 } else { leftArr[i] = queue[len(queue) - 1] } queue = append(queue, i) } rightArr := make([]int, n) queue = []int{} for i := n - 1; i >= 0; i-- { num := arr[i] for len(queue) > 0 && arr[queue[len(queue) - 1]] >= num { queue = queue[:len(queue) - 1] } if len(queue) == 0 { rightArr[i] = n } else { rightArr[i] = queue[len(queue) - 1] } queue = append(queue, i) } ans := 0 const MOD = 1000000007 for i, num := range arr { ans = (ans + num * (i - leftArr[i]) * (rightArr[i] - i)) % MOD } return ans }
|