We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b45ac80 commit 3bbed28Copy full SHA for 3bbed28
Python/sum-of-subarray-ranges.py
@@ -0,0 +1,27 @@
1
+# Time: O(n)
2
+# Space: O(n)
3
+
4
+class Solution(object):
5
+ def subArrayRanges(self, nums):
6
+ """
7
+ :type nums: List[int]
8
+ :rtype: int
9
10
+ result = 0
11
+ stk = []
12
+ for i in xrange(len(nums)+1):
13
+ x = nums[i] if i < len(nums) else float("inf")
14
+ while stk and nums[stk[-1]] <= x:
15
+ j = stk.pop()
16
+ k = stk[-1] if stk else -1
17
+ result += nums[j]*(j-k)*(i-j)
18
+ stk.append(i)
19
20
21
+ x = nums[i] if i < len(nums) else float("-inf")
22
+ while stk and nums[stk[-1]] >= x:
23
24
25
+ result -= nums[j]*(j-k)*(i-j)
26
27
+ return result
0 commit comments