300. Longest Increasing Subsequence

class Solution {
public:
    int lengthOfLIS(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> dp(n, 1);
        for(int i = 1; i < n; i++)
        {
            for(int j = 0; j < i; j++)
            {
                if(nums[i] > nums[j])
                {
                    dp[i] = max(dp[i], dp[j] + 1);
                }
            }
        }
        return *max_element(dp.begin(), dp.end());
    }
};
  • T: O(N2)O(N^2)
  • S: O(N)O(N)

Use lower_bound

class Solution {
public:
    int lengthOfLIS(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> pq;
        pq.push_back(nums[0]);
        for (int i = 1; i < n; i++)
        {
            if (nums[i] > pq.back())
            {
                pq.push_back(nums[i]);
            }
            else
            {
                int j = lower_bound(pq.begin(), pq.end(), nums[i]) - pq.begin();
                pq[j] = nums[i];
            }
        }
        return pq.size();
    }
};
  • T: O(NlogN)O(N \cdot \log N)
  • S: O(N)O(N)