- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of Python from the credited upstream file minimum-cost-to-make-two-binary-strings-equal.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 minimumCost(self, s, t, flipCost, swapCost, crossCost):7 """8 :type s: str9 :type t: str10 :type flipCost: int11 :type swapCost: int12 :type crossCost: int13 :rtype: int14 """15 cnt = [0]*216 for i in xrange(len(s)):17 if s[i] == t[i]:18 continue19 cnt[ord(s[i])-ord('0')] += 120 mn, mx = min(cnt[0], cnt[1]), max(cnt[0], cnt[1])21 q, r = divmod(mx-mn, 2)22 return mn*min(swapCost, 2*flipCost)+q*min(crossCost+swapCost, 2*flipCost)+r*flipCost23 24 25262728class Solution2(object):29 def minimumCost(self, s, t, flipCost, swapCost, crossCost):30 """31 :type s: str32 :type t: str33 :type flipCost: int34 :type swapCost: int35 :type crossCost: int36 :rtype: int37 """38 cnt = [0]*239 for i in xrange(len(s)):40 if s[i] == t[i]:41 continue42 cnt[ord(s[i])-ord('0')] += 143 mn, mx = min(cnt[0], cnt[1]), max(cnt[0], cnt[1])44 q, r = divmod(mx-mn, 2)45 return min((mx+mn)*flipCost, mn*swapCost+(mx-mn)*flipCost, mn*swapCost+q*(crossCost+swapCost)+r*flipCost)46