Re: More Concise or Idiomatic Max Sub-Array?

113 views
Skip to first unread message

Jean Niklas L'orange

unread,
Sep 29, 2012, 11:10:27 AM9/29/12
to clo...@googlegroups.com
Is there a more concise implementation, perhaps using `filter` or merely by making the `reduce` version more "idiomatic" somehow?
 
Another version I believe is more evident utilizes reductions to build a list over all the max-ending-heres. You can then just pick the maximal value in that list, giving you the maximal subarray:

(defn max-subarray [A]
  (let [pos+ (fn [sum x] (if (neg? sum) x (+ sum x)))
        ending-heres (reductions pos+ 0 A)]
    (reduce max ending-heres)))

noahlz

unread,
Sep 30, 2012, 11:54:57 PM9/30/12
to clo...@googlegroups.com
Great use of reductions. Thanks!
Reply all
Reply to author
Forward
0 new messages