From beb6ef92c7db29dd94c513a4a3009ac4f883b6cf Mon Sep 17 00:00:00 2001 From: Swapnil Sengupta Date: Wed, 30 Sep 2020 20:23:41 +0530 Subject: [PATCH 1/2] Add LongestIncreasingSubsequence.py --- .../LongestIncreasingSubsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/Dynamic Programming/LongestIncreasingSubsequence.py diff --git a/Python/Dynamic Programming/LongestIncreasingSubsequence.py b/Python/Dynamic Programming/LongestIncreasingSubsequence.py new file mode 100644 index 00000000..a97c5bd4 --- /dev/null +++ b/Python/Dynamic Programming/LongestIncreasingSubsequence.py @@ -0,0 +1,17 @@ +""" +Given an unsorted array of integers, this algorithm finds the length of the longest increasing subsequence. +""" +# nums is the input array which may be unsorted +def lengthOfLIS(nums): + if not nums: + return 0 + dp = [1 for i in range(len(nums))] # the dp array + longest = 1 # variable to keep track of the longest increasing subsequence at every iteration + for i in range(1, len(nums)): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + longest = max(dp[i], longest) # check if the length of LIS has changed + return longest + +print(lengthOfLIS([10,9,2,5,3,7,101,18])) \ No newline at end of file From 612d1051ed62c6596c7ebf483aec46dc4773b577 Mon Sep 17 00:00:00 2001 From: Swapnil Sengupta Date: Wed, 30 Sep 2020 20:23:41 +0530 Subject: [PATCH 2/2] Add LongestIncreasingSubsequence.py --- .../LongestIncreasingSubsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/Dynamic Programming/LongestIncreasingSubsequence.py diff --git a/Python/Dynamic Programming/LongestIncreasingSubsequence.py b/Python/Dynamic Programming/LongestIncreasingSubsequence.py new file mode 100644 index 00000000..a97c5bd4 --- /dev/null +++ b/Python/Dynamic Programming/LongestIncreasingSubsequence.py @@ -0,0 +1,17 @@ +""" +Given an unsorted array of integers, this algorithm finds the length of the longest increasing subsequence. +""" +# nums is the input array which may be unsorted +def lengthOfLIS(nums): + if not nums: + return 0 + dp = [1 for i in range(len(nums))] # the dp array + longest = 1 # variable to keep track of the longest increasing subsequence at every iteration + for i in range(1, len(nums)): + for j in range(i): + if nums[j] < nums[i]: + dp[i] = max(dp[i], dp[j] + 1) + longest = max(dp[i], longest) # check if the length of LIS has changed + return longest + +print(lengthOfLIS([10,9,2,5,3,7,101,18])) \ No newline at end of file