|
| 1 | + |
| 2 | +/** |
| 3 | + * @file |
| 4 | + * @brief find the length of the Longest Increasing Subsequence (LIS) |
| 5 | + * using Binary Search(https://en.wikipedia.org/wiki/Longest_increasing_subsequence) |
| 6 | + * @details |
| 7 | + * Given an integer array nums, return the length of the longest strictly |
| 8 | + * increasing subsequence. |
| 9 | + * The longest increasing subsequence is described as a subsequence of an array |
| 10 | + * where: All elements of the subsequence are in increasing order. This subsequence |
| 11 | + * itself is of the longest length possible. |
| 12 | +
|
| 13 | + * For solving this problem we have Three Approaches :- |
| 14 | +
|
| 15 | + * Approach 1 :- Using Brute Force |
| 16 | + * The first approach that came to your mind is the Brute Force approach where we |
| 17 | + * generate all subsequences and then manually filter the subsequences whose |
| 18 | + * elements come in increasing order and then return the longest such subsequence. |
| 19 | + * Time Complexity :- O(2^n) |
| 20 | + * It's time complexity is exponential. Therefore we will try some other |
| 21 | + * approaches. |
| 22 | +
|
| 23 | + * Approach 2 :- Using Dynamic Programming |
| 24 | + * To generate all subsequences we will use recursion and in the recursive logic we |
| 25 | + * will figure out a way to solve this problem. Recursive Logic to solve this |
| 26 | + * problem:- |
| 27 | + * 1. We only consider the element in the subsequence if the element is grater then |
| 28 | + * the last element present in the subsequence |
| 29 | + * 2. When we consider the element we will increase the length of subsequence by 1 |
| 30 | + * Time Complexity: O(N*N) |
| 31 | + * Space Complexity: O(N*N) + O(N) |
| 32 | +
|
| 33 | + * This approach is better then the previous Brute Force approach so, we can |
| 34 | + * consider this approach. |
| 35 | +
|
| 36 | + * But when the Constraints for the problem is very larger then this approach fails |
| 37 | +
|
| 38 | + * Approach 3 :- Using Binary Search |
| 39 | + * Other approaches use additional space to create a new subsequence Array. |
| 40 | + * Instead, this solution uses the existing nums Array to build the subsequence |
| 41 | + * array. We can do this because the length of the subsequence array will never be |
| 42 | + * longer than the current index. |
| 43 | +
|
| 44 | + * Time complexity: O(n∗log(n)) |
| 45 | + * Space complexity: O(1) |
| 46 | +
|
| 47 | + * This approach consider Most optimal Approach for solving this problem |
| 48 | +
|
| 49 | + * @author [Naman Jain](https://github.com/namanmodi65) |
| 50 | + */ |
| 51 | + |
1 | 52 | #include <cassert> /// for std::assert
|
2 | 53 | #include <iostream> /// for IO operations
|
3 | 54 | #include <vector> /// for std::vector
|
|
0 commit comments