|
| 1 | +/* A Naive Java Program for LIS Implementation */ |
| 2 | +class LIS { |
| 3 | + static int max_ref; // stores the LIS |
| 4 | + |
| 5 | + /* To make use of recursive calls, this function must |
| 6 | + return two things: 1) Length of LIS ending with element |
| 7 | + arr[n-1]. We use max_ending_here for this purpose 2) |
| 8 | + Overall maximum as the LIS may end with an element |
| 9 | + before arr[n-1] max_ref is used this purpose. |
| 10 | + The value of LIS of full array of size n is stored in |
| 11 | + *max_ref which is our final result */ |
| 12 | + static int _lis(int arr[], int n) |
| 13 | + { |
| 14 | + // base case |
| 15 | + if (n == 1) |
| 16 | + return 1; |
| 17 | + |
| 18 | + // 'max_ending_here' is length of LIS ending with |
| 19 | + // arr[n-1] |
| 20 | + int res, max_ending_here = 1; |
| 21 | + |
| 22 | + /* Recursively get all LIS ending with arr[0], |
| 23 | + arr[1] ... arr[n-2]. If arr[i-1] is smaller |
| 24 | + than arr[n-1], and max ending with arr[n-1] needs |
| 25 | + to be updated, then update it */ |
| 26 | + for (int i = 1; i < n; i++) { |
| 27 | + res = _lis(arr, i); |
| 28 | + if (arr[i - 1] < arr[n - 1] |
| 29 | + && res + 1 > max_ending_here) |
| 30 | + max_ending_here = res + 1; |
| 31 | + } |
| 32 | + |
| 33 | + // Compare max_ending_here with the overall max. And |
| 34 | + // update the overall max if needed |
| 35 | + if (max_ref < max_ending_here) |
| 36 | + max_ref = max_ending_here; |
| 37 | + |
| 38 | + // Return length of LIS ending with arr[n-1] |
| 39 | + return max_ending_here; |
| 40 | + } |
| 41 | + |
| 42 | + // The wrapper function for _lis() |
| 43 | + static int lis(int arr[], int n) |
| 44 | + { |
| 45 | + // The max variable holds the result |
| 46 | + max_ref = 1; |
| 47 | + |
| 48 | + // The function _lis() stores its result in max |
| 49 | + _lis(arr, n); |
| 50 | + |
| 51 | + // returns max |
| 52 | + return max_ref; |
| 53 | + } |
| 54 | + |
| 55 | + // driver program to test above functions |
| 56 | + public static void main(String args[]) |
| 57 | + { |
| 58 | + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; |
| 59 | + int n = arr.length; |
| 60 | + System.out.println("Length of lis is " + lis(arr, n) |
| 61 | + + "\n"); |
| 62 | + } |
| 63 | +} |
0 commit comments