Reverse Pairs (LC-0493)

class Solution:
    def reversePairs(self, nums):
        
        # process assuming both subarrays are in ascending order:
        def calc_rpairs(A, lx, mx, rx):

            A1 = A[lx:mx + 1]
            A2 = A[mx + 1:rx + 1]
            
            count = 0
            a1x, a2x = 0, 0

            # calculate the count first:
            while a1x < len(A1) and a2x < len(A2):
                if A1[a1x] > 2 * A2[a2x]:
                    count += len(A1) - a1x
                    a2x += 1
                else:
                    a1x += 1
            
            ix = lx
            a1x, a2x = 0, 0

            # now merge it in ascending order:
            while a1x < len(A1) and a2x < len(A2):
                if A1[a1x] <= A2[a2x]:
                    A[ix] = A1[a1x]
                    a1x += 1
                else:
                    A[ix] = A2[a2x]
                    a2x += 1
                ix += 1
            
            while a1x < len(A1):
                A[ix] = A1[a1x]
                a1x += 1
                ix += 1

            while a2x < len(A2):
                A[ix] = A2[a2x]
                a2x += 1
                ix += 1
            
            return count

        def dnc(A, lx, rx):
            count = 0
            if lx < rx:
                mx = lx + (rx - lx) // 2
                count += dnc(A, lx, mx)
                count += dnc(A, mx + 1, rx)
                count += calc_rpairs(A, lx, mx, rx)
            return count
        
        return dnc(nums, 0, len(nums) - 1)