You given an array:
3, 2, 1, 6, 5, 4, 9, 8, 7
you have to find a 3 tuple which has property a < b < c, also a is before b, b is before c in array.
Answer can have multiple tuples, you have to find any one.
In this array, answer will be 3, 6, 9
answer:
O(n) time algorithm: Use the same classic algorithm for Longest Increasing Subsequence, breaking when you find a subsequence of length 3.
-Using Patience Sort --- O(n) OR
-Using Dynamic Programming --- O(n*n)
make a binary search tree from a given array
try to get right side of node which full fill this condition
package com.zhuyu_deng.test;
public class Test
{
static int a[] = new int[] { 3, 2, 1, 6, 5, 4, 9, 8, 7 };
static int c[] = new int[a.length];
public static void main(String args[])
{
int b[] = new int[a.length];
for (int i = 0; i < b.length; ++i)
b[i] = 1;
for (int i = 1; i < a.length; ++i)
{
int maxLen = 1;
for (int j = 0; j < i; ++j)
{
if (a[j] < a[i] && b[j] + 1 > maxLen)
{
maxLen = b[j] + 1;
b[i] = maxLen;
c[i] = j;
}
if (maxLen >= 3)
break;
}
if (maxLen >= 3)
{
print(i);
System.out.println();
break;
}
}
}
private static void print(int x)
{
if (x != 0)
{
print(c[x]);
System.out.print(a[x] + " ");
} else
{
System.out.print(a[x] + " ");
}
}
}
package com.zhuyu_deng.test;
import java.util.ArrayList;
import java.util.List;
public class Test
{
static int[] array = new int[] { 3, 2, 1, 6, 5, 4, 9, 8, 7 };
static String finalString = "";
public static void main(String[] args)
{
List<String> touples = new ArrayList<String>();
for (int i = 0; i < array.length; i++)
{
getAllTouples(touples, i, 0);
}
System.out.println(touples);
}
public static List<String> getAllTouples(List<String> touples, int index, Integer pos)
{
int pivotElement = array[index];
for (int i = index + 1; i < array.length; i++)
{
if (pivotElement < array[i] && pos < i)
{
finalString = finalString + pivotElement;
if (finalString.length() == 2)
{
finalString = finalString + array[i];
touples.add(finalString);
finalString = finalString.substring(0, finalString.length() - 2);
pos = i;
i = index;
} else
{
getAllTouples(touples, i, pos);
finalString = finalString.substring(0, finalString.length() - 1);
}
}
}
return touples;
}
}