Skip to content

Add longest increasing subsequence #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 29, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Dynamic Programming/LongestIncreasingSubsequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import java.util.Scanner;

/**
*
* @author Afrizal Fikri (https://github.com/icalF)
*
*/
public class LongestIncreasingSubsequence {
public static void main(String[] args) throws Exception {

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

int ar[] = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = sc.nextInt();
}

System.out.println(LIS(ar));
}

private static int upperBound(int[] ar, int l, int r, int key) {
while (l < r-1) {
int m = (l + r) / 2;
if (ar[m] >= key)
r = m;
else
l = m;
}

return r;
}

public static int LIS(int[] array) {
int N = array.length;
if (N == 0)
return 0;

int[] tail = new int[N];
int length = 1; // always points empty slot in tail

tail[0] = array[0];
for (int i = 1; i < N; i++) {

// new smallest value
if (array[i] < tail[0])
tail[0] = array[i];

// array[i] extends largest subsequence
else if (array[i] > tail[length-1])
tail[length++] = array[i];

// array[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i]
// (and also, array[i] would have already appeared in one of LIS, identify the location and replace it)
else
tail[upperBound(tail, -1, length-1, array[i])] = array[i];
}

return length;
}
}