Problem 1: Longest Increasing Subsequence
Problem Statement: Given an array of integers, find the length of the longest strictly increasing subsequence.
Input
First line contains an integer n, the number of elements. The next line has n space-separated integers.
Output
Print the length of the longest increasing subsequence.
Examples
Input:
8
10 9 2 5 3 7 101 18
Output:
4
Solution Explanation
Method 1: Use an O(n log n) algorithm by maintaining a temporary list of potential sequence ends and using binary search to update this list. Method 2: Apply dynamic programming with O(n^2) time by comparing each element with all previous elements and tracking the maximum subsequence length ending at each position.
Solution in C++
#include
#include
#include
using namespace std;
int main(){
int n;
cin >> n;
vector arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
vector lis;
for (int x : arr) {
auto it = lower_bound(lis.begin(), lis.end(), x);
if(it == lis.end()) {
lis.push_back(x);
} else {
*it = x;
}
}
cout << lis.size();
return 0;
}