|
| 1 | +[](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust) |
| 2 | +[](https://github.com/LeetCode-in-Rust/LeetCode-in-Rust/fork) |
| 3 | + |
| 4 | +## 300\. Longest Increasing Subsequence |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +Given an integer array `nums`, return the length of the longest strictly increasing subsequence. |
| 9 | + |
| 10 | +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]`. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | +**Input:** nums = [10,9,2,5,3,7,101,18] |
| 15 | + |
| 16 | +**Output:** 4 |
| 17 | + |
| 18 | +**Explanation:** The longest increasing subsequence is [2,3,7,101], therefore the length is 4. |
| 19 | + |
| 20 | +**Example 2:** |
| 21 | + |
| 22 | +**Input:** nums = [0,1,0,3,2,3] |
| 23 | + |
| 24 | +**Output:** 4 |
| 25 | + |
| 26 | +**Example 3:** |
| 27 | + |
| 28 | +**Input:** nums = [7,7,7,7,7,7,7] |
| 29 | + |
| 30 | +**Output:** 1 |
| 31 | + |
| 32 | +**Constraints:** |
| 33 | + |
| 34 | +* `1 <= nums.length <= 2500` |
| 35 | +* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code> |
| 36 | + |
| 37 | +**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity? |
| 38 | + |
| 39 | +## Solution |
| 40 | + |
| 41 | +```rust |
| 42 | +impl Solution { |
| 43 | + pub fn length_of_lis(nums: Vec<i32>) -> i32 { |
| 44 | + if nums.is_empty() { |
| 45 | + return 0; |
| 46 | + } |
| 47 | + |
| 48 | + let mut dp = vec![i32::MAX; nums.len() + 1]; |
| 49 | + let (mut left, mut right) = (1, 1); |
| 50 | + |
| 51 | + for &curr in nums.iter() { |
| 52 | + let (mut start, mut end) = (left, right); |
| 53 | + |
| 54 | + // Binary search to find the position to update |
| 55 | + while start + 1 < end { |
| 56 | + let mid = start + (end - start) / 2; |
| 57 | + if dp[mid as usize] > curr { |
| 58 | + end = mid; |
| 59 | + } else { |
| 60 | + start = mid; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // Update the dp array |
| 65 | + if dp[start as usize] > curr { |
| 66 | + dp[start as usize] = curr; |
| 67 | + } else if curr > dp[start as usize] && curr < dp[end as usize] { |
| 68 | + dp[end as usize] = curr; |
| 69 | + } else if curr > dp[end as usize] { |
| 70 | + dp[end as usize + 1] = curr; |
| 71 | + right += 1; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + right |
| 76 | + } |
| 77 | +} |
| 78 | +``` |
0 commit comments