- 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
- 76 lines of Python from the credited upstream file fruits-into-baskets-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 numOfUnplacedFruits(self, fruits, baskets):7 """8 :type fruits: List[int]9 :type baskets: List[int]10 :rtype: int11 """12 class SegmentTree(object):13 def __init__(self, N,14 build_fn=lambda _: 0,15 query_fn=lambda x, y: y if x is None else x if y is None else max(x, y),16 update_fn=lambda x: x):17 self.tree = [None]*(2*2**((N-1).bit_length()))18 self.base = len(self.tree)219 self.query_fn = query_fn20 self.update_fn = update_fn21 for i in xrange(self.base, self.base+N):22 self.tree[i] = build_fn(i-self.base)23 for i in reversed(xrange(1, self.base)):24 self.tree[i] = query_fn(self.tree[2*i], self.tree[2*i+1])25 26 def update(self, i, h):27 x = self.base+i28 self.tree[x] = self.update_fn(h)29 while x > 1:30 x = 231 self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])32 33 def binary_search(self, x):34 if self.tree[1] < x:35 return -136 i = 137 while not i >= self.base:38 if self.tree[2*i] >= x:39 i = 2*i40 else:41 i = 2*i+142 return i-self.base43 44 def build(i):45 return baskets[i]46 47 st = SegmentTree(len(baskets), build_fn=build)48 result = 049 for x in fruits:50 i = st.binary_search(x)51 if i == -1:52 result += 153 else:54 st.update(i, 0)55 return result56 57 58596061class Solution2(object):62 def numOfUnplacedFruits(self, fruits, baskets):63 """64 :type fruits: List[int]65 :type baskets: List[int]66 :rtype: int67 """68 result = 069 for x in fruits:70 i = next((i for i in xrange(len(baskets)) if baskets[i] >= x), -1)71 if i ==-1:72 result += 173 else:74 baskets[i] = 075 return result76