|
| 1 | +# A naive Python implementation of LIS problem |
| 2 | + |
| 3 | +""" To make use of recursive calls, this function must return |
| 4 | +two things: |
| 5 | +1) Length of LIS ending with element arr[n-1]. We use |
| 6 | +max_ending_here for this purpose |
| 7 | +2) Overall maximum as the LIS may end with an element |
| 8 | +before arr[n-1] max_ref is used this purpose. |
| 9 | +The value of LIS of full array of size n is stored in |
| 10 | +*max_ref which is our final result """ |
| 11 | + |
| 12 | +# global variable to store the maximum |
| 13 | +global maximum |
| 14 | + |
| 15 | +def _lis(arr , n ): |
| 16 | + |
| 17 | + # to allow the access of global variable |
| 18 | + global maximum |
| 19 | + |
| 20 | + # Base Case |
| 21 | + if n == 1 : |
| 22 | + return 1 |
| 23 | + |
| 24 | + # maxEndingHere is the length of LIS ending with arr[n-1] |
| 25 | + maxEndingHere = 1 |
| 26 | + |
| 27 | + """Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] |
| 28 | + IF arr[n-1] is maller than arr[n-1], and max ending with |
| 29 | + arr[n-1] needs to be updated, then update it""" |
| 30 | + for i in range(1, n): |
| 31 | + res = _lis(arr , i) |
| 32 | + if arr[i-1] < arr[n-1] and res+1 > maxEndingHere: |
| 33 | + maxEndingHere = res +1 |
| 34 | + |
| 35 | + # Compare maxEndingHere with overall maximum. And |
| 36 | + # update the overall maximum if needed |
| 37 | + maximum = max(maximum , maxEndingHere) |
| 38 | + |
| 39 | + return maxEndingHere |
| 40 | + |
| 41 | +def lis(arr): |
| 42 | + |
| 43 | + # to allow the access of global variable |
| 44 | + global maximum |
| 45 | + |
| 46 | + # lenght of arr |
| 47 | + n = len(arr) |
| 48 | + |
| 49 | + # maximum variable holds the result |
| 50 | + maximum = 1 |
| 51 | + |
| 52 | + # The function _lis() stores its result in maximum |
| 53 | + _lis(arr , n) |
| 54 | + |
| 55 | + return maximum |
| 56 | + |
| 57 | +# Driver program to test the above function |
| 58 | +arr = [10 , 22 , 9 , 33 , 21 , 50 , 41 , 60] |
| 59 | +n = len(arr) |
| 60 | +print("Length of lis is ", lis(arr)) |
0 commit comments