DEV Community

codingpineapple
codingpineapple

Posted on

2 1

LeetCode 300. Longest Increasing Subsequence (javascript solution)

Description:

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

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n)

// Dynamic programming
var lengthOfLIS = function (nums) {
    // Create dp array
    const dp = Array.from(nums, () => 1);
    // Max subsequence length
    let max = 1
    // Check all increasing subsequences up to the current ith number in nums
    for (let i = 1; i < nums.length; i++) {
        // Keep track of subsequence length in the dp array
        for (let j = 0; j < i; j++) {
            // Only change dp value if the numbers are increasing
            if (nums[i] > nums[j]) {
                // Set the value to be the larget subsequence length
                dp[i] = Math.max(dp[i], dp[j] + 1)
                // Check if this subsequence is the largest
                max = Math.max(dp[i], max)
            }
        }
    }
  return max;
};
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
prateekool109 profile image
Satyagraha

Simple Explanation

youtube.com/watch?v=TGj3gsLF8uU

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay