a => // outer function taking a[]
n => // inner function taking n
(o = []) // o[] = array of [ value, group, index ] tuples
.map(a => // once o[] is finalized ...
a[2], // ... keep only the original indices
a.map((v, i) => [ v, i ]) // we first turn a[] into an array of
// [ value, index ] pairs
.sort(g = ([a], [b]) => // and sort them ...
b - a // ... from highest to lowest value
) //
.map(([v, i]) => // for each pair [ value, index ]:
( [p, q] = o.sort(g) // sort o[] by decreasing 'birth time'
.filter(a => // and keep only the tuples ...
a[1].some(j => // ... whose groups contain a value
(j -= i) * j < 2 // adjacent to the current value
) //
), // save at most 2 tuples that in [ p, q ]
q = q || [, []], // force a default dummy value for q
p // test p
) ? // if p is defined:
q[ //
p[1].push( // append to the group of p:
...q[1], // the values from the group of q
i // followed by i
), //
q[0] -= v, // subtract the 'dead time' from the
1 // 'birth time' of q
] = [] // and clear the group of q
: // else:
o.push([v, [i], i]) // create a new tuple [ value, group, index ]
) // end of inner map()
) // end of outer map()
.slice(0, n) // return only the n first elements