Longest Increasing Sub-Seq
Difficulty: Hard Topics: seqs
Given a vector of integers, find the longest consecutive sub-sequence of increasing numbers. If two sub-sequences have the same length, use the one that occurs first. An increasing sub-sequence must have a length of 2 or greater to qualify. test not run
- (= (__ [1 0 1 2 3 0 4 5]) [0 1 2 3])
- (= (__ [5 6 1 3 2 7]) [5 6])
- (= (__ [2 3 3 4 5]) [3 4 5])
- (= (__ [7 6 5 4]) [])
;; Misty
;; TODO 有部分不满足题意
(defn sub-seq [in]
{:pre [(vector? in)]}
(letfn [(compare [prev next]
(if (and (> (count next) 1) (> (count next) (count prev)))
next
prev))]
(loop [ret [] sub [(first in)] r (rest in)]
(if (seq sub)
(let [a (last sub)
b (first r)]
(if (= (inc a) b)
(recur ret (conj sub b) (rest r))
(recur (compare ret sub) (when b [b]) (rest r))))
ret))))
;; Lo
(fn [v]
(let [subseqs (for [i (range (count v))
j (range (+ 2 i) (inc (count v)))]
(subvec v i j))]
(->> subseqs
(filter #(apply < %))
reverse ;have to reverse here as max-key returns the last element if count is the same
(apply max-key count [])))) ;have to add in a blank vector here, in case there is no increasing subvec