Tuesday 15 October 2013

Sorted subsequence of size 3 in O(n) time and O(n) extra space

#include<stdio.h>
#include<stdlib.h>
void size3Subsequence(int arr[], int n)
{
    int max = n-1, min=0, i;
     int *smaller = (int*)malloc(sizeof(int)*n);
     smaller[0] = -1;
     for (i = 1; i < n; i++)
    {
        if (arr[i] <= arr[min])
        {
            min = i;
            smaller[i] = -1;
        }
       
        else
            smaller[i] = min;
   }

    for (i = n-2; i >= 0; i--)
    {
        if (arr[i] >= arr[max])
            max = i;

        else if(smaller[i]!=-1)
        {
            printf("%d %d %d\n", arr[smaller[i]], arr[i], arr[max]);
                free(smaller);
            return;
        }  
    }

    printf("No such triplet found\n");
    free(smaller);
    return;
}

int main()
{
    int arr[] = {1,3,0, 2, 5, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    size3Subsequence(arr, n);
    return 0;
}

No comments:

Post a Comment