I have an array of size N. This array consists of numbers from 1 to N, and they are not repeated, and they are at random order. How can I determine the length of an maximum increasing sequence? The longest increasing subsequence (LIS) problem is to find a subsequence of a given sequence in which the subsequence elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique. LIS is solvable in time O(n log n), where n is the length of the input sequence. As a base, I took the algorithm from GeeksforGeeks site. I fixed few bugs in this algorithm and programmed it in C#.

- class LongestIncr_ingSubseq
- {
- public Int32 LongestIncrSubseq(Int32[] sourceArray)
- {
- Int32 lengthSourceArray = sourceArray.Length;
- Int32[] tailIndices = new Int32[lengthSourceArray];
- Int32[] prevIndices = new Int32[lengthSourceArray];
- Int32 maxLength = 1;
- tailIndices[0] = 0;
- prevIndices[0] = -1;
- for (Int32 i = 1; i < lengthSourceArray; i++)
- {
- if (sourceArray[i] < sourceArray[tailIndices[0]])
- tailIndices[0] = i;
- else if (sourceArray[i] > sourceArray[tailIndices[maxLength - 1]])
- {
- prevIndices[i] = tailIndices[maxLength - 1];
- tailIndices[maxLength++] = i;
- }
- else
- {
- Int32 pos =
- GetCeilIndex(sourceArray, tailIndices, -1, maxLength - 1, sourceArray[i]);
- prevIndices[i] = tailIndices[pos - 1 < 0 ? 0 : pos - 1];
- tailIndices[pos] = i;
- }
- }
- for (Int32 i = tailIndices[maxLength - 1],
- j = maxLength, l = lengthSourceArray - 1; j > 0; i = prevIndices[i], j--)
- tailIndices[l--] = sourceArray[i];
- for (Int32 i = lengthSourceArray - maxLength, j = maxLength; j > 0; j--)
- Console.WriteLine("LIS " + String.Format("{0} ", tailIndices[i++]));
- return maxLength;
- }
- Int32 GetCeilIndex(Int32[] sourceArray, Int32[] tailIndices, Int32 l, Int32 r, Int32 key)
- {
- Int32 m;
- while( r - l > 1 )
- {
- m = l + (r - l)/2;
- if (sourceArray[tailIndices[m]] >= key) r = m;
- else l = m;
- }
- return r;
- }
- }

## No comments:

## Post a Comment