From a17b48e1a6dbdac042aa5b959a2d75d5ccaa9b02 Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Sat, 20 Jan 2024 15:22:47 -0500 Subject: 907 --- 907/main.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100755 907/main.py diff --git a/907/main.py b/907/main.py new file mode 100755 index 0000000..0cca2e0 --- /dev/null +++ b/907/main.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +import typing + + +class Solution: + def sumSubarrayMins(self, arr: typing.List[int]) -> int: + n = len(arr) + left = [-1] * n + right = [n] * n + stack = [] + + for i, value in enumerate(arr): + while stack and arr[stack[-1]] >= value: + stack.pop() + if stack: + left[i] = stack[-1] + stack.append(i) + + stack = [] + + for i in range(n - 1, -1, -1): + while stack and arr[stack[-1]] > arr[i]: + stack.pop() + if stack: + right[i] = stack[-1] + stack.append(i) + + mod = 10**9 + 7 + + result = ( + sum((i - left[i]) * (right[i] - i) * value for i, value in enumerate(arr)) + % mod + ) + + return result + + +def main(): + solution = Solution() + print(solution.sumSubarrayMins([3, 1, 2, 4])) + print(solution.sumSubarrayMins([11, 81, 94, 43, 3])) + + +if __name__ == "__main__": + main() -- cgit v1.2.3