Crates.io | longest-increasing-subsequence |
lib.rs | longest-increasing-subsequence |
version | 0.1.0 |
source | src |
created_at | 2019-04-03 22:32:20.540537 |
updated_at | 2019-04-03 22:32:20.540537 |
description | Find a longest increasing subsequence of some input sequence |
homepage | |
repository | https://github.com/fitzgen/longest-increasing-subsequence |
max_upload_size | |
id | 125745 |
size | 28,757 |
longest-increasing-subsequence
The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.
For example, consider this sequence of integers:
2, 9, 4, 7, 3, 4, 5
The longest increasing subsequence (LIS) for this sequence is 2, 3, 4, 5.
Note that there is not always a singular LIS. Consider this sequence:
2, 6, 5
In this sequence, both 2, 5 and 2, 6 are LISs.
This crate exposes two functions for finding a longest increasing subsequence within a slice:
The high-level, easy-to-use lis
function takes any slice of T: Ord
and
returns the LIS as a vector of indices into that slice.
The low-level lis_with
function takes a custom comparator and lets you
bring your own allocations (which lets you choose to reuse allocations or use a
custom allocator).
Both functions use the same underlying algorithm. They execute in O(n log n) time and use O(n) memory.
use longest_increasing_subsequence::lis;
let xs = vec![9, 2, 8, 3, 5];
for i in lis(&xs) {
println!("{} at index {}", xs[i], i);
}
// Prints:
// 2 at index 1
// 3 at index 3
// 5 at index 4