最长连续递增序列

  1. pub fn longest_continuous_increasing_subsequence<T: Ord>(input_array: &[T]) -> &[T] {
  2. let length: usize = input_array.len();
  3. //Handle the base cases
  4. if length <= 1 {
  5. return input_array;
  6. }
  7. //Create the array to store the longest subsequence at each location
  8. let mut tracking_vec = vec![1; length];
  9. //Iterate through the input and store longest subsequences at each location in the vector
  10. for i in (0..length - 1).rev() {
  11. if input_array[i] < input_array[i + 1] {
  12. tracking_vec[i] = tracking_vec[i + 1] + 1;
  13. }
  14. }
  15. //Find the longest subsequence
  16. let mut max_index: usize = 0;
  17. let mut max_value: i32 = 0;
  18. for (index, value) in tracking_vec.iter().enumerate() {
  19. if value > &max_value {
  20. max_value = *value;
  21. max_index = index;
  22. }
  23. }
  24. &input_array[max_index..max_index + max_value as usize]
  25. }
  26. #[cfg(test)]
  27. mod tests {
  28. use super::longest_continuous_increasing_subsequence;
  29. #[test]
  30. fn test_longest_increasing_subsequence() {
  31. //Base Cases
  32. let base_case_array: [i32; 0] = [];
  33. assert_eq!(
  34. &longest_continuous_increasing_subsequence(&base_case_array),
  35. &[]
  36. );
  37. assert_eq!(&longest_continuous_increasing_subsequence(&[1]), &[1]);
  38. //Normal i32 Cases
  39. assert_eq!(
  40. &longest_continuous_increasing_subsequence(&[1, 2, 3, 4]),
  41. &[1, 2, 3, 4]
  42. );
  43. assert_eq!(
  44. &longest_continuous_increasing_subsequence(&[1, 2, 2, 3, 4, 2]),
  45. &[2, 3, 4]
  46. );
  47. assert_eq!(
  48. &longest_continuous_increasing_subsequence(&[5, 4, 3, 2, 1]),
  49. &[5]
  50. );
  51. assert_eq!(
  52. &longest_continuous_increasing_subsequence(&[5, 4, 3, 4, 2, 1]),
  53. &[3, 4]
  54. );
  55. //Non-Numeric case
  56. assert_eq!(
  57. &longest_continuous_increasing_subsequence(&['a', 'b', 'c']),
  58. &['a', 'b', 'c']
  59. );
  60. assert_eq!(
  61. &longest_continuous_increasing_subsequence(&['d', 'c', 'd']),
  62. &['c', 'd']
  63. );
  64. }
  65. }