Output: 3
Sequences: 1 4 6, 1 4 5, 1 2 5
Question is a variant of longest increasing sub sequence problem(LIS Problem) or longest consecutive elements
See http://en.wikipedia.org/wiki/Longest_increasing_subsequence
Data Structure: Array
Algorithm:LIS
Working Code:By Manu
import java.io.*
class LISOfLengthK
{
private static void lisOfLengthK(Integer [] inputArray, int k) {
int n = inputArray.length, temp, count;
Integer [] best = new Integer[n];
Integer [] last = new Integer[n];
Integer [] outputArray = new Integer[k];
for(int i=0;i
best[j] = best[i]+1;
last[j] = i;
if(best[j] == k) {
temp = j;
count =0;
outputArray[count++] = inputArray[temp];
while(last[temp] != -1) {
outputArray[count++] = inputArray[last[temp]];
temp = last[temp];
}
for(int index=k-1;index>=0;index--)
System.out.print(outputArray[index] + " ");
System.out.println();
}
}
}
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Integer [] inputArray = new Integer[n];
for(int i=0;i
int k = Integer.parseInt(br.readLine());
lisOfGivenLength(inputArray, k);
}
}
Time Complexity O(N^2)
Space Complexity O(1)
https://ideone.com/Jbtw0
5 comments :
please xplain the logicc
@dolphia As i said its variation standard problem LIS . i suggest you to read out the same first from wiki then if you face the any problem will be happy to help :)
Shashank
given code is not correct..
for input {1,2,5,6,8}it wont print :-
2,5,6
5,6,8
i have modified the given code..now it will print correct output.
please let me know if it fails.
void LIS(int arr[],int len,int k)
{
int i,j,dp[20],pre[20],pos,p,k_tmp,c;
for(i=0;i arr[i])
{
dp[j]=dp[i]+1;
pre[j]=i;
if(dp[j]==k)
{
pos=j;
printf("\n");
k_tmp=dp[j];
while(k_tmp > 0)
{
printf("%d ",arr[pos]);
pos=pre[pos];
k_tmp--;
}
dp[j]=dp[j]-1;
}
}
}
}
}
@Atul .. Can You Explain The Algorithm ?
Thanks
Dolphia
Post a Comment