Given a list of distinct positive integers, I am trying to find the largest subset that forms an arithmetic sequence with a given difference D.
For example, given D = 5, with the set of numbers 1, 5, 10, 6, 7, 8, 15, 11 the longest sequence would be 5, 10, 15
I have tried to use union-findusing sets to solve this but am unsure if my solution actually works in practice.
I first add every element tocan't find a union-findsolution faster than (disjoint-set) data structure. This takes O(n) time$O(n^2)$. For example, I then iterate through each numberhave tried adding all items in the original list of numbers, and performarray to a find()TreeSet
on each number + D to check if its successor is in the union-find. If it isThis automatically orders the elements, thenafter which I union()
brute force check all the number with its successorpossible sequences.
While I do this, Am I storeon the largest subset in a separate variable, and update it when needed.
Whatright lines or is the catch in my approach? Since union and find operations have an amortized cost of O(1), surely mythere a better approach would be O(n)?