From 437b3464279ad051bc2e1fd85f41340dd449bd22 Mon Sep 17 00:00:00 2001 From: meet-soni5720 <43992307+meet-soni5720@users.noreply.github.com> Date: Sun, 13 Oct 2019 12:38:19 +0530 Subject: [PATCH] Add files via upload --- Algorithms/Dynamic Programming/lis_length.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Algorithms/Dynamic Programming/lis_length.cpp diff --git a/Algorithms/Dynamic Programming/lis_length.cpp b/Algorithms/Dynamic Programming/lis_length.cpp new file mode 100644 index 0000000..3ea00ed --- /dev/null +++ b/Algorithms/Dynamic Programming/lis_length.cpp @@ -0,0 +1,59 @@ +// Length of Longest Increasing Subsequence +//n(logn) time complexity +#include +#include + +// Binary search (note boundaries in the caller) +int CeilIndex(std::vector& v, int l, int r, int key) +{ + while (r - l > 1) { + int m = l + (r - l) / 2; + if (v[m] >= key) + r = m; + else + l = m; + } + + return r; +} + +int LongestIncreasingSubsequenceLength(std::vector& v) +{ + if (v.size() == 0) + return 0; + + std::vector tail(v.size(), 0); + int length = 1; // always points empty slot in tail + + tail[0] = v[0]; + for (size_t i = 1; i < v.size(); i++) { + + // new smallest value + if (v[i] < tail[0]) + tail[0] = v[i]; + + // v[i] extends largest subsequence + else if (v[i] > tail[length - 1]) + tail[length++] = v[i]; + + // v[i] will become end candidate of an existing + // subsequence or Throw away larger elements in all + // LIS, to make room for upcoming grater elements + // than v[i] (and also, v[i] would have already + // appeared in one of LIS, identify the location + // and replace it) + else + tail[CeilIndex(tail, -1, length - 1, v[i])] = v[i]; + } + + return length; +} + +int main() +{ + std::vector v; + v.push_back(2);v.push_back(5);v.push_back(3);v.push_back(7);v.push_back(11);v.push_back(8);v.push_back(10);v.push_back(13);v.push_back(6); + std::cout << "Length of Longest Increasing Subsequence is " + << LongestIncreasingSubsequenceLength(v) << '\n'; + return 0; +}