Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Jan 20, 2024
1 parent 27ce95f commit 2709faf
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions leetcode/907.SumofSubarrayMinimums/sumofSubarrayMinimums.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// https://leetcode.com/problems/sum-of-subarray-minimums

package main

import (
"fmt"
)

func sumSubarrayMins(arr []int) int {
const mod int = 1e9 + 7

n := len(arr)
left := make([]int, n)
right := make([]int, n)
for i := range left {
left[i] = -1
right[i] = n
}

stk := []int{}
for i, v := range arr {
for len(stk) > 0 && arr[stk[len(stk)-1]] >= v {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
left[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}

stk = []int{}
for i := n - 1; i >= 0; i-- {
for len(stk) > 0 && arr[stk[len(stk)-1]] > arr[i] {
stk = stk[:len(stk)-1]
}
if len(stk) > 0 {
right[i] = stk[len(stk)-1]
}
stk = append(stk, i)
}

result := 0
for i, v := range arr {
result += (i - left[i]) * (right[i] - i) * v % mod
result %= mod
}

return result
}

func main() {
arr := []int{11, 81, 94, 43, 3}

fmt.Println(sumSubarrayMins(arr))
}

0 comments on commit 2709faf

Please sign in to comment.