I have a sequence of integers {a1,a2...an} and I want to divide it into minimum number of "increasing subsequences". For example: let the sequence be {10,30,20,40}, then the answer would be 2. In this case, the first increasing sequence would be {10,30,40} and the second would be {20}. I am able to do it using an O(N^2) algorithm but I'm particularly interested in an O(N*logN) solution which could serve the purpose.
Asked
Active
Viewed 2,627 times
4
-
what's the condition for separating the sequence? I can't see why {10,30,20,40} should be split exactly into that, and not something different – lenz Jun 10 '13 at 12:21
-
Isn't the minimum number zero? Unless it's sorted. – Novak Jun 10 '13 at 12:39
-
I am sorry. I missed out the most crucial word - "increasing". I have edited the question. Its fixed now. – divanshu Jun 10 '13 at 13:23
1 Answers
6
This could be done with simple greedy algorithm.
Keep sorted array of subsequences found so far. Sorted in decreasing order, by the value of the last integer in each sequence. Initially empty.
Get first not-yet-processed element from the sequence and find the subsequence where the last integer is smaller than this element but larger (or equal) than in all such subsequences. Use binary search here to get overall complexity O(N log N). If no such subsequence found, add a new one at the end of the array. Add this element to this subsequence. Repeat while there are not-yet-processed elements in the sequence.

Evgeny Kluev
- 24,287
- 7
- 55
- 98
-
A sorted array of subsequences? I believe there can be 2^n such subsequences in the worst case? – divanshu Jun 10 '13 at 14:41
-
@divanshu: no, in the worst case there are exactly N subsequences of length 1 each (when the original sequence is sorted in decreasing order). – Evgeny Kluev Jun 10 '13 at 14:50
-
2+1: It might be worth adding that this problem is known as "Patience sorting" – Peter de Rivaz Jun 10 '13 at 18:32
-