|
| 1 | +//! # Longest Increasing Subsequence |
| 2 | +
|
| 3 | +/// # Example |
| 4 | +/// ``` |
| 5 | +/// use programming_team_code_rust::helpers::lis::Lis; |
| 6 | +/// |
| 7 | +/// let a = [1, 1, -2, 1]; |
| 8 | +/// |
| 9 | +/// let mut lis = Lis::default(); |
| 10 | +/// for &num in &a { |
| 11 | +/// lis.push(num); |
| 12 | +/// } |
| 13 | +/// |
| 14 | +/// assert_eq!(lis.dp.len(), 2); |
| 15 | +/// assert_eq!(lis.get_lis(), [2, 3]); |
| 16 | +/// |
| 17 | +/// lis.pop(); |
| 18 | +/// |
| 19 | +/// assert_eq!(lis.dp.len(), 1); |
| 20 | +/// assert_eq!(lis.get_lis(), [2]); |
| 21 | +/// ``` |
| 22 | +#[derive(Default)] |
| 23 | +pub struct Lis<T> { |
| 24 | + /// dp\[i\].0 = smallest number such that there exists a LIS of length i+1 ending in this number |
| 25 | + /// dp\[i\].1 = index in original array of dp\[i\].0 |
| 26 | + pub dp: Vec<(T, usize)>, |
| 27 | + #[allow(clippy::type_complexity)] |
| 28 | + st: Vec<(Option<usize>, Option<(usize, (T, usize))>)>, |
| 29 | +} |
| 30 | + |
| 31 | +impl<T: Copy + Ord> Lis<T> { |
| 32 | + /// Pushes new_elem onto back of vec |
| 33 | + /// |
| 34 | + /// # Complexity |
| 35 | + /// - n: length of vec |
| 36 | + /// - Time: O(log(LIS.len())) |
| 37 | + /// - Space: O(n) total |
| 38 | + pub fn push(&mut self, new_elem: T) { |
| 39 | + // change to `elem <= new_elem` for longest non-decreasing subsequence |
| 40 | + let idx = self.dp.partition_point(|&(elem, _)| elem < new_elem); |
| 41 | + let mut prev = None; |
| 42 | + if idx == self.dp.len() { |
| 43 | + self.dp.push((new_elem, self.st.len())); |
| 44 | + } else { |
| 45 | + prev = Some((idx, self.dp[idx])); |
| 46 | + self.dp[idx] = (new_elem, self.st.len()); |
| 47 | + } |
| 48 | + self.st.push(( |
| 49 | + match idx { |
| 50 | + 0 => None, |
| 51 | + _ => Some(self.dp[idx - 1].1), |
| 52 | + }, |
| 53 | + prev, |
| 54 | + )); |
| 55 | + } |
| 56 | + |
| 57 | + /// Pop off back of vec |
| 58 | + /// |
| 59 | + /// # Complexity |
| 60 | + /// - Time: O(1) |
| 61 | + /// - Space: O(1) |
| 62 | + pub fn pop(&mut self) { |
| 63 | + let (_, prev) = self.st.pop().unwrap(); |
| 64 | + if let Some((idx, prev)) = prev { |
| 65 | + self.dp[idx] = prev; |
| 66 | + } else { |
| 67 | + self.dp.pop(); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /// Gets indexes of LIS of vec |
| 72 | + /// |
| 73 | + /// # Complexity |
| 74 | + /// - Time: O(LIS.len()) |
| 75 | + /// - Space: O(LIS.len()) |
| 76 | + pub fn get_lis(&self) -> Vec<usize> { |
| 77 | + if self.dp.is_empty() { |
| 78 | + return Vec::new(); |
| 79 | + } |
| 80 | + let mut idxs = Vec::with_capacity(self.dp.len()); |
| 81 | + let mut idx = self.dp.last().unwrap().1; |
| 82 | + idxs.push(idx); |
| 83 | + while let Some(prev) = self.st[idx].0 { |
| 84 | + idx = prev; |
| 85 | + idxs.push(idx); |
| 86 | + } |
| 87 | + idxs.reverse(); |
| 88 | + idxs |
| 89 | + } |
| 90 | +} |
0 commit comments