Longest Increasing Subsequence, DP solution

Problem is here: https://leetcode.com/problems/longest-increasing-subsequence/description/:

Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 
Note:
  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
The solution below is the N^2. Use DP for it: keep track of the best sequence for all elements 0..i-1 using O(n) space. Then it is an easy O(n) time check for element i. Code is below, cheers, Boris.

public class Solution
{
public int LengthOfLIS(int[] nums)
{
if (nums == null || nums.Length == 0) return 0;

int[] longest = new int[nums.Length];

int retVal = 1;
longest[0] = 1;
for (int i = 1; i < longest.Length; i++)
{
longest[i] = 1;
for (int j = 0; j < i; j++)
longest[i] = nums[i] > nums[j] ? Math.Max(longest[i], longest[j] + 1) : longest[i];
retVal = Math.Max(longest[i], retVal);
}

return retVal;
}
}

Comments

  1. Classics of dynamic programming :)

    class Solution {
    public:
    int lengthOfLIS(const vector& nums) {
    if (nums.empty()) return 0;
    vector d(nums.size(), 1);
    for (int i = 1; i < nums.size(); ++i) {
    for (int j = 0; j < i; ++j) {
    if (nums[j] < nums[i] && d[j] + 1 > d[i]) {
    d[i] = d[j] + 1;
    }
    }
    }
    return *max_element(d.cbegin(), d.cend());
    }
    };

    https://gist.github.com/ttsugriy/2f7a5ad5ab69289412adc49be6a37328

    I also love the O(N*log(N)) solution because it shows how it's possible to view the same DP problem from a different angle :)

    ReplyDelete

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons