forked from dharmanshu1921/Website-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_increasing_subsequence.cpp
More file actions
56 lines (45 loc) · 1.28 KB
/
Longest_increasing_subsequence.cpp
File metadata and controls
56 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* A Memoization Java Program for LIS Implementation */
import java.util.Arrays;
import java.lang.*;
class LIS {
/* To make use of recursive calls, this function must
return two things: 1) Length of LIS ending with element
arr[n-1]. We use max_ending_here for this purpose 2)
Overall maximum as the LIS may end with an element
before arr[n-1] max_ref is used this purpose.
The value of LIS of full array of size n is stored in
*max_ref which is our final result */
static int f(int idx, int prev_idx, int n, int a[],
int[][] dp)
{
if (idx == n) {
return 0;
}
if (dp[idx][prev_idx + 1] != -1) {
return dp[idx][prev_idx + 1];
}
int notTake = 0 + f(idx + 1, prev_idx, n, a, dp);
int take = Integer.MIN_VALUE;
if (prev_idx == -1 || a[idx] > a[prev_idx]) {
take = 1 + f(idx + 1, idx, n, a, dp);
}
return dp[idx][prev_idx + 1] = Math.max(take, notTake);
}
// The wrapper function for _lis()
static int lis(int arr[], int n)
{
// The function _lis() stores its result in max
int dp[][] = new int[n+1][n+1];
for (int row[] : dp)
Arrays.fill(row, -1);
return f(0, -1, n, arr, dp);
}
// driver program to test above functions
public static void main(String args[])
{
int a[] = { 3, 10, 2, 1, 20 };
int n = a.length;
System.out.println("Length of lis is " + lis(a, n)
+ "\n");
}
}