Counting maximum number of elements in right order
This is a classical LCS problem, which can be solved in DP as suggested by earlier post. Time Complexity of the implementation is O(mn) which is much better than the original code implementation. (An exercise for the reader to study. ;-)
The next code fragment assumes that the source/target are both strings.
Here is the DP approach:
class Solution:

def lcs(self, source: str, target: str) -&gt; int:
    n,  m = len(source), len(target)
    dp = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(n):
        for j in range(m):
            if source[i] == target[j]:
                dp[i + 1][j + 1]= dp[i][j] + 1
            else:
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
    return dp[-1][-1]