Skip to content

Commit 3bbed28

Browse files
authored
Create sum-of-subarray-ranges.py
1 parent b45ac80 commit 3bbed28

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Python/sum-of-subarray-ranges.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
stk = []
20+
for i in xrange(len(nums)+1):
21+
x = nums[i] if i < len(nums) else float("-inf")
22+
while stk and nums[stk[-1]] >= x:
23+
j = stk.pop()
24+
k = stk[-1] if stk else -1
25+
result -= nums[j]*(j-k)*(i-j)
26+
stk.append(i)
27+
return result

0 commit comments

Comments
 (0)