Longest Snake Sequence in an Array

前端 未结 1 853
别那么骄傲
别那么骄傲 2021-01-07 04:46

Question : A set of numbers separated by space is passed as input. The program must print the largest snake sequence present in the numbers. A snake sequenc

1条回答
  •  孤街浪徒
    2021-01-07 05:22

    Assuming that the order in the original set of numbers does not matter, as seems to be the case in your question, this seems to be an instance of the Longest Path Problem, which is NP-hard.

    Think of it that way: You can create a graph from your numbers, with edges between all pairs of nodes that have a difference of one. Now, the longest simple (acyclic) path in this graph is your solution. Your first example would correspond to this graph and path. (Note that there are two 1 nodes for the two ones in the input set.)

    enter image description here

    While this in itself does not solve your problem, it should help you getting started finding an algorithm to solve (or approximate) it, now that you know a better/more common name for the problem.


    One algorithm works like this: Starting from each of the numbers, determine the "adjacent" numbers and do sort of a depth-first search through the graph to determine the longest path. Remember to temporarily remove the visited nodes from the graph. This has a worstcase complexity of O(2n) 1), but apparently it's sufficient for your examples.

    def longest_snake(numbers, counts, path):
        best = path
        for n in sorted(counts, key=numbers.index):
            if counts[n] > 0 and (path == [] or abs(path[-1] - n) == 1):
                counts[n] -= 1
                res = longest_snake(numbers, counts, path + [n])
                if len(res) > len(best):
                    best = res
                counts[n] += 1
        return best
    

    Example:

    >>> from collections import Counter
    >>> numbers = list(map(int, "9 8 7 5 3 0 1 -2 -3 1 2".split()))
    >>> longest_snake(numbers, Counter(numbers), [])
    [3, 2, 1, 0, 1]
    

    Note that this algorithm will reliably find a maximum "snake" sequence, using no number more often than allowed. However, it may not find the specific sequence that's expected as the output, i.e. "the snake sequence appearing in the natural input order", whatever that's supposed to mean. To get closer to the "natural order", you might try the numbers in the same order as they appear in the input (as I did with sorted), but that does not work perfectly, either. Anyway, I'm sure you can figure out the rest by yourself.


    1) In this special case, the graph has a branching factor of 2, thus O(2n); in the more general case, the complexity would be closer to O(n!).

    0 讨论(0)
提交回复
热议问题