Longest subarray whose elements form a continuous sequence

后端 未结 7 854
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 05:52

Given an unsorted array of positive integers, find the length of the longest subarray whose elements when sorted are continuous. Can you think of an O(n) solution?

Examp

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 06:09

    Don't get your hopes up, this is only a partial answer.

    I'm quite confident that the problem is not solvable in O(n). Unfortunately, I can't prove it.

    If there is a way to solve it in less than O(n^2), I'd suspect that the solution is based on the following strategy:

    1. Decide in O(n) (or maybe O(n log n)) whether there exists a continuous subarray as you describe it with at least i elements. Lets call this predicate E(i).
    2. Use bisection to find the maximum i for which E(i) holds.

    The total running time of this algorithm would then be O(n log n) (or O(n log^2 n)).

    This is the only way I could come up with to reduce the problem to another problem that at least has the potential of being simpler than the original formulation. However, I couldn't find a way to compute E(i) in less than O(n^2), so I may be completely off...

提交回复
热议问题