algoadvance

Leetcode 300. Longest Increasing Subsequence

Problem Statement

Given an integer array nums, return the length of the longest strictly increasing subsequence.

Example:

Input: nums = [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.

Constraints:

Clarifying Questions

  1. Can the input array contain duplicates?
    • Yes, but the subsequence has to strictly increase, meaning duplicates cannot be part of the same subsequence.
  2. Is the longest increasing subsequence (LIS) required, or just its length?
    • Only the length of the longest increasing subsequence is required.

Strategy

To solve this problem, we can use Dynamic Programming (DP). Here’s a detailed plan:

  1. DP Array Initialization:
    • Let dp[i] represent the length of the longest increasing subsequence that ends with the element at index i.
  2. State Transition:
    • For each element nums[i], check all previous elements nums[j] where (j < i) and nums[j] < nums[i]. Update dp[i] to be the maximum of dp[i] and dp[j] + 1.
  3. Base Case:
    • Every element itself can be a subsequence, so initialize dp[i] = 1 for all i.
  4. Result:
    • The length of the longest increasing subsequence will be the maximum value in the dp array.

Time Complexity

Code

#include <vector>
#include <algorithm>

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

Explanation:

Thus, the algorithm efficiently computes the length of the longest increasing subsequence in O(N^2) time complexity.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI