Find maximum non contiguous subarray that respect a specific rule
I will move my comment to an answer, since you seemed to indicate that the comment solved your problem.

Your problem is normally called the Longest Common Subsequence problem. It does not require the common subsequence to be contiguous. It can be solved efficiently with dynamic programming, and it is an early example of dynamic programming in many textbooks.

There are many implementations of LCS available online. The wiki article on LCS I linked to in the above comment is a good place to start.