This approach uses dynamic programming to solve the problem in O(n^2) time complexity. We maintain a dp array where dp[i] represents the length of the longest increasing subsequence that ends with nums[i]. For each element, we iterate over all previous elements to see if they can be included in the subsequence ending at the current element, and update dp[i] accordingly.
Time Complexity: O(n^2) where n is the length of the input array. Space Complexity: O(n) for storing the dp array.
1class Solution:
2 def lengthOfLIS(self, nums):
3 if not nums:
4 return 0
5 dp = [1] * len(nums)
6 max_len = 1
7 for i in range(1, len(nums)):
8 for j in range(i):
9 if nums[i] > nums[j]:
10 dp[i] = max(dp[i], dp[j] + 1)
11 max_len = max(max_len, dp[i])
12 return max_len
13
14# Example usage:
15nums = [10,9,2,5,3,7,101,18]
16sol = Solution()
17print(sol.lengthOfLIS(nums))
In Python, we use a list comprehension to initialize the dp array, then apply the nested loops to update the dp as in other examples.
In this approach, we use a combination of dynamic programming and binary search to solve the problem in O(n log n) time. This is often called the 'patience sorting' technique where we maintain a list, 'ends', to store the smallest ending value of any increasing subsequence with length i+1 in 'ends[i]'. We use binary search to find the position where each element in nums can be placed in 'ends'.
Time Complexity: O(n log n). Space Complexity: O(n).
1function lengthOfLIS(nums) {
2 const ends = [];
3 for (let num of nums) {
4 let i = 0, j = ends.length;
5 while (i < j) {
6 let mid = Math.floor((i + j) / 2);
7 if (ends[mid] < num) i = mid + 1;
8 else j = mid;
9 }
10 if (i < ends.length) ends[i] = num;
11 else ends.push(num);
12 }
13 return ends.length;
14}
15
16console.log(lengthOfLIS([10,9,2,5,3,7,101,18]));
This JavaScript solution manual implements binary search to find the point each number should install in the 'ends' array. If it's a new longest subsequence, it's added; if not, it replaces the element at the found position.