Algo-Sim › Dynamic Programming

Longest Increasing Subsequence

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

dp[i] is the longest increasing run ending at i: one more than the best dp[j] over earlier, smaller nums[j].

Problem

Given an integer array nums, return the length of its longest strictly increasing subsequence. A subsequence keeps the original order but may skip elements.

Constraints

Edge cases to test

Follow-up questions

Can you do better than O(n²)?
Patience sorting: keep the smallest tail of each length and binary search where each value goes: O(n log n).
How do you rebuild the sequence?
Store a parent index for each element (in either method) and walk back from the end of the longest run.
What about counting the LIS?
Keep (length, count) per index and add counts of equal-length predecessors (LC 673): O(n²).

Solution

Java

public int lengthOfLIS(int[] nums) {
    int[] dp = new int[nums.length];
    Arrays.fill(dp, 1);
    int best = 1;
    for (int i = 1; i < nums.length; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[j] < nums[i]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
        best = Math.max(best, dp[i]);
    }
    return best;
}

Python

def length_of_lis(nums):
    dp = [1] * len(nums)
    best = 1
    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)
        best = max(best, dp[i])
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int lengthOfLIS(vector<int> &nums) {
        vector<int> dp(int(nums.size()));
        fill(dp.begin(), dp.end(), 1);
        int best = 1;
        for (int i = 1; i < int(nums.size()); i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = std::max(dp[i], dp[j] + 1);
                }
            }
            best = std::max(best, dp[i]);
        }
        return best;
    }
};

More Dynamic Programming problems