Skip to content

Instantly share code, notes, and snippets.

@lnikon
Last active March 22, 2019 13:54
Show Gist options
  • Save lnikon/8406d0dd1bbeab41f9aca9b581761c72 to your computer and use it in GitHub Desktop.
Save lnikon/8406d0dd1bbeab41f9aca9b581761c72 to your computer and use it in GitHub Desktop.
Longest Increasing subsequence
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
template <class ForwardIterator, class Comp = std::less<>>
auto lis(ForwardIterator begin,
ForwardIterator end,
Comp comp = Comp()) {
const auto length = std::distance(begin, end);
auto maxs = std::vector<size_t>(length, 1);
for(auto newBegin{begin}; newBegin != end; ++newBegin) {
auto fromBeginToNewBegin = std::distance(begin, newBegin);
for(auto beginCopy {begin}; beginCopy != newBegin; ++beginCopy) {
auto fromBeginToBeginCopy = std::distance(begin, beginCopy);
if(comp(*beginCopy, *newBegin)) {
maxs[fromBeginToNewBegin]
= std::max( maxs[fromBeginToNewBegin],
maxs[fromBeginToBeginCopy] + 1);
}
}
}
return *std::max_element(std::begin(maxs), std::end(maxs));
}
int main()
{
auto seq = std::vector<int>{6, 2, 10, 0, 8, 4, 12, 1, 7, 3, 11, 1, 9, 5, 13};
auto lisLen = lis(std::begin(seq), std::end(seq));
std::cout << "lisLen: " << lisLen << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment