function first_pass(l, n) {
var nsum = new Array(l.length - n);
var running = 0;
n -= 1;
for (var i = 0; i < n; ++i) {
running += l[i];
}
for (var i = 0; i < l.length - n; ++i) {
running += l[i+n];
nsum[i] = running;
running -= l[i];
}
return nsum;
}
function lazy_insertion_sort(a, b, c) {
var i, j;
c -= 1;
for (i = j = c; i < a.length; ++i) {
if (b[a[i]] > b[a[j]]) {
j = i;
}
}
i = a[c];
a[c] = a[j];
a[j] = i;
}
function magic(J, K, jsum, ksum, n) {
var num_available = 0;
var jsum_best_indices = jsum.map((x,i)=>i);
var ksum_best_indices = ksum.map((x,i)=>i);
while (num_available < n) {
num_available += 1
lazy_insertion_sort(jsum_best_indices, jsum, num_available)
lazy_insertion_sort(ksum_best_indices, ksum, num_available)
var max = -1;
for (var jbi = 0; jbi < num_available; jbi += 1) {
var kbi = num_available - jbi - 1;
var ji = jsum_best_indices[jbi];
var ki = ksum_best_indices[kbi];
if ((ji < ki && ki - ji > J) ||
(ki < jbi && jbi - kbi > K)) {
var candidate = ksum[ki] + jsum[ji]
if (candidate > max) {
max = candidate;
}
}
}
if (max > -1) {
return max;
}
}
throw "The number of trees is too low.";
}
document.getElementById("run").addEventListener("click", function () {
var J = +document.getElementById("J").value;
var K = +document.getElementById("K").value;
var l = eval(document.getElementById("array").value);
var jsum = first_pass(l, J);
var ksum = first_pass(l, K);
document.getElementById("output").innerText = magic(J, K, jsum, ksum, l.length);
});
Array: <input id="array" value="[1, 1, 1, 2, 2, 5, 6, 7, 5, 2, 2, 3, 1, 1, 1]"/><br />
J: <input id="J" type="number" value="3" /><br />
K: <input id="K" type="number" value="4" /><br />
<button id="run">Run</button>
Output: <span id="output"></span>