-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sum-of-imbalance-numbers-of-all-subarrays.py
43 lines (40 loc) · 1.34 KB
/
sum-of-imbalance-numbers-of-all-subarrays.py
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
37
38
39
40
41
42
43
# Time: O(n)
# Space: O(n)
# hash table, combinatorics
class Solution(object):
def sumImbalanceNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right = [len(nums)]*len(nums)
lookup = [len(nums)]*((len(nums)+1)+1)
for i in reversed(xrange(len(nums))):
right[i] = min(lookup[nums[i]], lookup[nums[i]+1]) # to avoid duplicated count
lookup[nums[i]] = i
result = left = 0
lookup = [-1]*((len(nums)+1)+1)
for i in xrange(len(nums)):
left = lookup[nums[i]+1]
lookup[nums[i]] = i
result += (i-left)*(right[i]-i)
return result - (len(nums)+1)*len(nums)//2 # since we overcount 1 in each subarray, we have to subtract all of them
# Time: O(n^2)
# Space: O(n)
# hash table, two pointers
class Solution2(object):
def sumImbalanceNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for right in xrange(len(nums)):
lookup = {nums[right]}
curr = 0
for left in reversed(xrange(right)):
if nums[left] not in lookup:
lookup.add(nums[left])
curr += 1-(nums[left]-1 in lookup)-(nums[left]+1 in lookup)
result += curr
return result