#increasing #longest #subsequence #sequence #find #input #lis

longest-increasing-subsequence

Find a longest increasing subsequence of some input sequence

1 unstable release

0.1.0 Apr 3, 2019

#962 in Algorithms

Download history 3544/week @ 2024-07-22 3485/week @ 2024-07-29 3885/week @ 2024-08-05 4246/week @ 2024-08-12 3469/week @ 2024-08-19 4115/week @ 2024-08-26 4160/week @ 2024-09-02 3638/week @ 2024-09-09 3893/week @ 2024-09-16 4607/week @ 2024-09-23 4702/week @ 2024-09-30 5142/week @ 2024-10-07 6807/week @ 2024-10-14 6722/week @ 2024-10-21 7140/week @ 2024-10-28 6867/week @ 2024-11-04

27,931 downloads per month
Used in 191 crates (5 directly)

MIT/Apache

12KB
80 lines

longest-increasing-subsequence

Build Status

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.

Wikipedia

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.

API

This crate exposes two functions for finding a longest increasing subsequence within a slice:

  1. 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.

  2. 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.

Example

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

No runtime deps