{"id":25350,"date":"2017-10-15T17:10:35","date_gmt":"2017-10-15T11:40:35","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25350"},"modified":"2018-10-31T16:26:46","modified_gmt":"2018-10-31T10:56:46","slug":"python-programming-longest-increasing-subsequence","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-longest-increasing-subsequence\/","title":{"rendered":"Longest Increasing Subsequence"},"content":{"rendered":"<p><span style=\"color: #003300;\"><strong>Longest Increasing Subsequence:<\/strong><\/span><\/p>\n<p>We have discussed <a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-overlapping-subproblems-property\/\">Overlapping Subproblems<\/a> and<a href=\"https:\/\/www.wikitechy.com\/technology\/optimal-substructure-property\/\" target=\"_blank\" rel=\"noopener\"> Optimal Substructure<\/a> properties respectively.<span id=\"more-12832\"><\/span><\/p>\n<p>Let us discuss <strong>Longest Increasing Subsequence<\/strong> (LIS) problem as an example problem that can be solved using <a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-min-cost-path\/\" target=\"_blank\" rel=\"noopener\">Dynamic Programming<\/a>.<br \/>\nThe Longest Increasing Subsequence (<strong>LIS<\/strong>) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are <a href=\"https:\/\/www.wikitechy.com\/technology\/algorithm-in-c-median-of-two-sorted-arrays\/\" target=\"_blank\" rel=\"noopener\">sorted<\/a> in increasing order. <strong>For example<\/strong>, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25327\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Longest-Increasing-Subsequence.png\" alt=\"Longest-Increasing-Subsequence\" width=\"779\" height=\"89\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Longest-Increasing-Subsequence.png 779w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Longest-Increasing-Subsequence-300x34.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Longest-Increasing-Subsequence-768x88.png 768w\" sizes=\"(max-width: 779px) 100vw, 779px\" \/><\/p>\n<p><span style=\"color: #800000;\"><strong>More Examples:<\/strong><\/span><\/p>\n<pre>Input  : arr[] = {3, 10, 2, 1, 20}\r\nOutput : Length of LIS = 3\r\nThe longest increasing subsequence is 3, 10, 20\r\n\r\nInput  : arr[] = {3, 2}\r\nOutput : Length of LIS = 1\r\nThe longest increasing subsequences are {3} and {2}\r\n\r\nInput : arr[] = {50, 3, 10, 7, 40, 80}\r\nOutput : Length of LIS = 4\r\nThe longest increasing subsequence is {3, 7, 40, 80}<\/pre>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"optimal-substructure\"><span style=\"color: #000080;\"><strong>Optimal Substructure:<\/strong><\/span><\/h3>\n<p>Let <strong>arr[0..n-1]<\/strong> be the input <a href=\"https:\/\/www.wikitechy.com\/tutorials\/javascript\/remove-empty-elements-from-an-array-in\" target=\"_blank\" rel=\"noopener\">array<\/a> and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS.<br \/>\nThen, L(i) can be recursively written as:<br \/>\n<strong>L(i) = 1 + max( L(j) )<\/strong> where 0 &lt; j &lt; i and arr[j] &lt; arr[i]; or<br \/>\n<strong>L(i) = 1<\/strong>, if no such j exists.<br \/>\nTo find the LIS for a given array, we need to return <strong>max(L(i))<\/strong> where 0 &lt; i &lt; n.<br \/>\nThus, we see the LIS problem satisfies the optimal substructure property as the main problem can be solved using solutions to subproblems.<\/p>\n<p>Following is a simple recursive implementation of the LIS problem. It follows the recursive structure discussed above.<\/p>\n<p><span style=\"color: #993300;\"><strong>Python Programming<\/strong><\/span><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># A naive Python based recursive implementation of LIS problem<br\/> <br\/>global max_lis_length # stores the final LIS<br\/> <br\/># Recursive implementation for calculating the LIS<br\/>def _lis(arr, n):<br\/>    # Following declaration is needed to allow modification<br\/>    # of the global copy of max_lis_length in _lis()<br\/>    global max_lis_length<br\/> <br\/>    # Base Case<br\/>    if n == 1:<br\/>        return 1<br\/> <br\/>    current_lis_length = 1<br\/> <br\/>    for i in xrange(0, n-1):<br\/>        # Recursively calculate the length of the LIS<br\/>        # ending at arr[i]<br\/>        subproblem_lis_length = _lis(arr, i)<br\/> <br\/>        # Check if appending arr[n-1] to the LIS<br\/>        # ending at arr[i] gives us an LIS ending at<br\/>        # arr[n-1] which is longer than the previously<br\/>        # calculated LIS ending at arr[n-1]<br\/>        if arr[i] &lt; arr[n-1] and \\<br\/>            current_lis_length &lt; (1+subproblem_lis_length):<br\/>            current_lis_length = (1+subproblem_lis_length)<br\/> <br\/>    # Check if currently calculated LIS ending at<br\/>    # arr[n-1] is longer than the previously calculated<br\/>    # LIS and update max_lis_length accordingly<br\/>    if (max_lis_length &lt; current_lis_length):<br\/>        max_lis_length = current_lis_length<br\/> <br\/>    return current_lis_length<br\/> <br\/># The wrapper function for _lis()<br\/>def lis(arr, n):<br\/> <br\/>    # Following declaration is needed to allow modification<br\/>    # of the global copy of max_lis_length in lis()<br\/>    global max_lis_length<br\/> <br\/>    max_lis_length = 1 # stores the final LIS<br\/> <br\/>    # max_lis_length is declared global at the top<br\/>    # so that it can maintain its value<br\/>    # between the recursive calls of _lis()<br\/>    _lis(arr , n)<br\/> <br\/>    return max_lis_length<br\/> <br\/># Driver program to test the functions above<br\/>def main():<br\/>    arr = [10, 22, 9, 33, 21, 50, 41, 60]<br\/>    n = len(arr)<br\/>    print &quot;Length of LIS is&quot;, lis(arr, n)<br\/> <br\/>if __name__==&quot;__main__&quot;:<br\/>    main()<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output :<\/strong><\/span><\/h3>\n<pre>Length of LIS is 5<\/pre>\n<h3 id=\"overlapping-subproblems\"><span style=\"color: #000080;\"><strong>Overlapping Subproblems :<\/strong><\/span><\/h3>\n<p>Considering the above implementation, following is recursion tree for an array of size 4. <strong>lis(n)<\/strong> gives us the length of LIS for arr[].<\/p>\n<pre>              lis(4)\r\n        \/        |     \\\r\n      lis(3)    lis(2)   lis(1)\r\n     \/   \\        \/\r\n   lis(2) lis(1) lis(1)\r\n   \/\r\nlis(1)\r\n<\/pre>\n<p>We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memorization or Tabulation. Following is a tabluated implementation for the LIS problem.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><span style=\"color: #993300;\"><strong>Python\u00a0Programming<\/strong><\/span><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Dynamic programming Python implementation of LIS problem<br\/> <br\/># lis returns length of the longest increasing subsequence<br\/># in arr of size n<br\/>def lis(arr):<br\/>    n = len(arr)<br\/> <br\/>    # Declare the list (array) for LIS and initialize LIS<br\/>    # values for all indexes<br\/>    lis = [1]*n<br\/> <br\/>    # Compute optimized LIS values in bottom up manner<br\/>    for i in range (1 , n):<br\/>        for j in range(0 , i):<br\/>            if arr[i] &gt; arr[j] and lis[i]&lt; lis[j] + 1 :<br\/>                lis[i] = lis[j]+1<br\/> <br\/>    # Initialize maximum to 0 to get the maximum of all<br\/>    # LIS<br\/>    maximum = 0<br\/> <br\/>    # Pick maximum of all LIS values<br\/>    for i in range(n):<br\/>        maximum = max(maximum , lis[i])<br\/> <br\/>    return maximum<br\/># end of lis function<br\/> <br\/># Driver program to test above function<br\/>arr = [10, 22, 9, 33, 21, 50, 41, 60]<br\/>print &quot;Length of lis is&quot;, lis(arr)<\/code><\/pre> <\/div>\n<h3 id=\"output-2\"><span style=\"color: #008000;\"><strong>Output :<\/strong><\/span><\/h3>\n<pre>Length of lis is 5<\/pre>\n<p>Note that the time complexity of the above Dynamic Programming (DP) solution is <strong>O(n^2)<\/strong> and there is a <strong>O(nLogn)<\/strong> solution for the LIS problem.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Python Programming &#8211; Longest Increasing Subsequence &#8211; Dynamic Programming &#8211; LIS problem is to find the length of the longest subsequence of a given sequence<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,70145,83517],"tags":[72847,72842,72993,70483,72848,72840,72846,72994,72843,72992,72854,72844,72850,72839,72977,72979,72995,72978,72975,72981,72980,72976,72852,72855,72853,72851],"class_list":["post-25350","post","type-post","status-publish","format-standard","hentry","category-coding","category-dynamic-programming","category-python-programming","tag-concept-of-dynamic-programming","tag-define-dynamic-programming","tag-definition-of-dynamic-programming-in-python","tag-dynamic-programming","tag-dynamic-programming-code-generation-algorithm","tag-dynamic-programming-definition","tag-dynamic-programming-in-data-structure","tag-dynamic-programming-in-python","tag-dynamic-programming-problems","tag-dynamic-programming-python","tag-dynamic-programming-set-1","tag-dynamic-programming-software","tag-explain-dynamic-programming","tag-how-to-solve-dynamic-programming-problems","tag-longest-increasing-subsequence-c","tag-longest-increasing-subsequence-code","tag-longest-increasing-subsequence-in-python","tag-longest-increasing-subsequence-java","tag-longest-increasing-subsequence-nlogn","tag-longest-increasing-subsequence-recursive","tag-longest-increasing-subsequence-youtube","tag-longest-increasing-subsequences","tag-problems-on-dynamic-programming","tag-simple-dynamic-programming-example","tag-types-of-dynamic-programming","tag-youtube-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25350","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25350"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25350\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25350"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25350"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25350"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}