Skip to content

Instantly share code, notes, and snippets.

@fahied
Created December 2, 2014 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahied/f347d9d3cca245dd9024 to your computer and use it in GitHub Desktop.
Save fahied/f347d9d3cca245dd9024 to your computer and use it in GitHub Desktop.
to find the longest increasing contiguous subsequence
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define ARRAY_SIZE(A) sizeof(A)/sizeof(A[0])
//-------------------------------------------- Reverse Array Using Pointer ----------------------------------------------//
void printArray (int *array)
{
/* loop until null is found */
for(int i = 0; array[ i ]; i++)
{
printf("%d", array[ i ]);
}
}
//-------------------------------------------- Reverse Array Using Pointer ----------------------------------------------//
void reverse_array(int *pointer, int n)
{
int *s, c, d;
s = (int*)malloc(sizeof(int)*n);
if( s == NULL )
exit(0);
for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )
*(s+d) = *(pointer+c);
for ( c = 0 ; c < n ; c++ )
*(pointer+c) = *(s+c);
free(s);
}
//-------------------------------------------- Find Ceil Index ----------------------------------------------//
// Binary search (note boundaries in the caller)
// A[] is ceilIndex in the caller
int CeilIndex(int A[], int l, int r, int key) {
int m;
while( r - l > 1 ) {
m = l + (r - l)/2;
(A[m] >= key ? r : l) = m; // ternary expression returns an l-value
}
return r;
}
//-------------------------------------- Lonest Increasing Subsequence Length -----------------------------------//
int LongestIncreasingSubsequenceLength(int A[], int size) {
// Add boundary case, when array size is one
int *tailTable = new int[size];
int len; // always points empty slot
memset(tailTable, 0, sizeof(tailTable[0])*size);
tailTable[0] = A[0];
len = 1;
for( int i = 1; i < size; i++ ) {
if( A[i] < tailTable[0] )
// new smallest value
tailTable[0] = A[i];
else if( A[i] > tailTable[len-1] )
// A[i] wants to extend largest subsequence
tailTable[len++] = A[i];
else
// A[i] wants to be current end candidate of an existing subsequence
// It will replace ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i];
}
reverse_array(tailTable, len);
printArray(tailTable);
delete[] tailTable;
return len;
}
int main() {
int A[] = { 2, 5, 3, 7, 11, 8, 10, 13, 6 };
int n = ARRAY_SIZE(A);
printf("Length of Longest Increasing Subsequence is %d\n",
LongestIncreasingSubsequenceLength(A, n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment