Lisp Max Counters
(defun max-counters (n a)
(let ((counters (make-array n :initial-element 0))
(max-counter 0)
(last-update 0)
(condition (1+ n)))
(dolist (v a)
(when (<= v n)
(let ((index (1- v)))
(when (< (aref counters index) last-update)
(setf (aref counters index) last-update))
(incf (aref counters index))
(setf max-counter (max max-counter (aref counters index)))))
(when (= v condition)
(setf last-update max-counter)))
(dotimes (k n)
(when (< (aref counters k) last-update)
(setf (aref counters k) last-update)))
(coerce counters 'list)))
This delays the expensive “set all counters to max” work until it is really needed, which keeps the solution fast.