- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 85 lines of Python from the credited upstream file longest-balanced-subarray-ii.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def longestBalanced(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 class SegmentTree(object):12 def __init__(self, N):13 self.min = [0]*(1<<((N-1).bit_length()+1))14 self.max = [0]*(1<<((N-1).bit_length()+1))15 self.base = len(self.min)>>116 self.lazy = [0]*self.base17 18 def __apply(self, x, val):19 self.min[x] += val20 self.max[x] += val21 if x < self.base:22 self.lazy[x] += val23 24 def __push(self, x):25 for h in reversed(xrange(1, x.bit_length())):26 y = x>>h27 if self.lazy[y]:28 self.__apply(y<<1, self.lazy[y])29 self.__apply((y<<1)|1, self.lazy[y])30 self.lazy[y] = 031 32 def update(self, L, R, h): 33 def pull(x):34 while x > 1:35 x >>= 136 self.min[x] = self.min[x<<1] if self.min[x<<1] < self.min[(x<<1)|1] else self.min[(x<<1)|1]37 self.max[x] = self.max[x<<1] if self.max[x<<1] > self.max[(x<<1)|1] else self.max[(x<<1)|1]38 if self.lazy[x]:39 self.min[x] += self.lazy[x]40 self.max[x] += self.lazy[x]41 42 L += self.base43 R += self.base44 L0, R0 = L, R45 while L <= R:46 if L & 1: 47 self.__apply(L, h)48 L += 149 if R & 1 == 0: 50 self.__apply(R, h)51 R -= 152 L >>= 153 R >>= 154 pull(L0)55 pull(R0)56 57 def binary_search(self, x):58 i = 159 while not i >= self.base:60 if self.lazy[i]:61 self.__apply(i<<1, self.lazy[i])62 self.__apply((i<<1)|1, self.lazy[i])63 self.lazy[i] = 064 i <<= 165 if not self.min[i] <= x <= self.max[i]:66 i |= 167 return i-self.base 68 69 n = len(nums)+170 st = SegmentTree(n)71 result = curr = 072 lookup = {}73 for i, x in enumerate(nums, 1):74 d = +1 if x&1 else -175 if x in lookup:76 st.update(lookup[x], n-1, -d)77 curr -= d78 curr += d79 lookup[x] = i80 st.update(lookup[x], n-1, +d)81 l = i-st.binary_search(curr)82 if l > result:83 result = l84 return result85