- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 62 lines of Python from the credited upstream file minimum-stability-factor-of-array.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 minStable(self, nums, maxC):7 """8 :type nums: List[int]9 :type maxC: int10 :rtype: int11 """12 def gcd(a, b):13 while b:14 a, b = b, a%b15 return a16 17 def binary_search_right(left, right, check):18 while left <= right:19 mid = left + (right-left)220 if not check(mid):21 right = mid-122 else:23 left = mid+124 return right25 26 27 28 29 30 31 class SparseTable(object):32 def __init__(self, arr, fn):33 self.fn = fn34 self.bit_length = [0]35 n = len(arr)36 k = n.bit_length()-1 37 for i in xrange(k+1):38 self.bit_length.extend(i+1 for _ in xrange(min(1<<i, (n+1)-len(self.bit_length))))39 self.st = [[0]*n for _ in xrange(k+1)]40 self.st[0] = arr[:]41 for i in xrange(1, k+1): 42 for j in xrange((n-(1<<i))+1):43 self.st[i][j] = fn(self.st[i-1][j], self.st[i-1][j+(1<<(i-1))])44 45 def query(self, L, R): 46 i = self.bit_length[R-L+1]-1 47 return self.fn(self.st[i][L], self.st[i][R-(1<<i)+1])48 49 def check(l):50 cnt = 051 i = 052 while i+l-1 < len(nums):53 if rmq.query(i, i+l-1) >= 2:54 cnt += 155 i += l56 else:57 i += 158 return cnt > maxC59 60 rmq = SparseTable(nums, gcd)61 return binary_search_right(1, len(nums), check)62