const maxMod3Path = (grid) =>
[...grid] .reverse () .reduce ((prev, row, ri) => row .map ((c, i) =>
[
...(prev [i - 1] || []).map(({n, p}) => ri == 0 ? {n, p} : ({n, p: 'L' + p})),
...(prev [i + 1] || []).map(({n, p}) => ri == 0 ? {n, p} : ({n, p: 'R' + p})),
]
.map (({n, p}) => ({n: n + c, p}))
.reduce (
(a, {n, p}) => {a [n % 3] = (n > a [n % 3] .n ? {n, p} : a [n % 3]); return a},
[{n: 0}, {n: 0}, {n: 0}]
)
),
grid [0] .map ((c) => [{n: 0, p: ''}, {n: 0, p: ''}, {n: 0, p: ''}])
)
.map (([{n, p}], startIndex) => ({total: n, path: p, startIndex}))
.reduce ((a, x) => x.total > a.total ? x : a, {total: 0})
const grid = [
[ 7, 6, 5, 4, 3, 2, 1 ],
[ 2, 4, 6, 8, 10, 12, 14 ],
[ 2, 7, 1, 8, 2, 8, 1 ],
[ 3, 1, 4, 1, 5, 9, 2 ],
[ 2, 3, 5, 7, 11, 13, 17 ],
[ 8, 6, 7, 5, 3, 0, 9 ],
]
console .log (maxMod3Path (grid))