LeetCode 0300. Longest Increasing Subsequence Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0300. Longest Increasing Subsequence

Description

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

 

Example 1:

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.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

 

Constraints:

  • 1 <= nums.length <= 2500
  • -104 <= nums[i] <= 104

 

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) f = [1] * n for i in range(1, n): for j in range(i): if nums[j] < nums[i]: f[i] = max(f[i], f[j] + 1) return max(f)(code-box)

Solution 2

PythonJavaC++GoTypeScript
class BinaryIndexedTree: def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, v: int): while x <= self.n: self.c[x] = max(self.c[x], v) x += x & -x def query(self, x: int) -> int: mx = 0 while x: mx = max(mx, self.c[x]) x -= x & -x return mx class Solution: def lengthOfLIS(self, nums: List[int]) -> int: s = sorted(set(nums)) m = len(s) tree = BinaryIndexedTree(m) for x in nums: x = bisect_left(s, x) + 1 t = tree.query(x - 1) + 1 tree.update(x, t) return tree.query(m)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !