Skip to content
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

Create longest-increasing-subsequence.py #76

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
51 changes: 51 additions & 0 deletions dp/longest-increasing-subsequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# A naive Python implementation of LIS problem

# global variable to store the maximum
global maximum

def _lis(arr , n ):

# to allow the access of global variable
global maximum

# Base Case
if n == 1 :
return 1

# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1

"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is maller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""
for i in xrange(1, n):
res = _lis(arr , i)
if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:
maxEndingHere = res +1

# Compare maxEndingHere with overall maximum. And
# update the overall maximum if needed
maximum = max(maximum , maxEndingHere)

return maxEndingHere

def lis(arr):

# to allow the access of global variable
global maximum

# lenght of arr
n = len(arr)

# maximum variable holds the result
maximum = 1

# The function _lis() stores its result in maximum
_lis(arr , n)

return maximum

# Driver program to test the above function
arr = [10 , 22 , 9 , 33 , 21 , 50 , 41 , 60]
n = len(arr)
print "Length of lis is ", lis(arr)