forked from rene-d/hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest-increasing-subsequent.cpp
81 lines (68 loc) · 1.9 KB
/
longest-increasing-subsequent.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// The Longest Increasing Subsequence
// Find the length of the longest increase subsequence in a given array.
//
// https://www.hackerrank.com/challenges/longest-increasing-subsequent/problem
//
#include <bits/stdc++.h>
using namespace std;
// C++ implementation to find longest increasing subsequence
// in O(n Log n) time.
// Binary search
int GetCeilIndex(int arr[], vector<int> &T, int l, int r,
int key)
{
while (r - l > 1)
{
int m = l + (r - l)/2;
if (arr[T[m]] >= key)
r = m;
else
l = m;
}
return r;
}
int LongestIncreasingSubsequence(int arr[], int n)
{
// Add boundary case, when array n is zero
// Depend on smart pointers
vector<int> tailIndices(n, 0); // Initialized with 0
vector<int> prevIndices(n, -1); // initialized with -1
int len = 1; // it will always point to empty location
for (int i = 1; i < n; i++)
{
if (arr[i] < arr[tailIndices[0]])
{
// new smallest value
tailIndices[0] = i;
}
else if (arr[i] > arr[tailIndices[len - 1]])
{
// arr[i] wants to extend largest subsequence
prevIndices[i] = tailIndices[len - 1];
tailIndices[len++] = i;
}
else
{
// arr[i] wants to be a potential condidate of
// future subsequence
// It will replace ceil value in tailIndices
int pos = GetCeilIndex(arr, tailIndices, -1,
len - 1, arr[i]);
prevIndices[i] = tailIndices[pos - 1];
tailIndices[pos] = i;
}
}
return len;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for(int arr_i = 0; arr_i < n; arr_i++){
cin >> arr[arr_i];
}
int result = LongestIncreasingSubsequence(&arr.at(0), arr.size() );
cout << result << endl;
return 0;
}