4Clojure #53 Longest Increasing Sub-Seq

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

转载于:https://my.oschina.net/u/580483/blog/482540

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值