Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Imperative solution in Clear category for Fast Train by juhokarppinen
const sum = (max, min) => ((max - min + 1) * (max + min)) / 2;
function fastTrain(sections: [number, number][]): number {
let speed = 0;
let time = 0;
let overshoot = 0;
let totalRemaining = sections.reduce((a, [b]) => a + b, 0);
sections.forEach(([length, limit], i) => {
const [, nextLimit] = sections[i + 1] || [0, 1];
let remaining = length + overshoot;
while (remaining > 0) {
if (speed < limit && sum(speed + 1, nextLimit) <= remaining + 1 && sum(speed + 1, 1) <= totalRemaining) {
speed += 1;
} else if (sum(speed, nextLimit) > remaining || sum(speed, 1) > totalRemaining) {
speed -= 1;
}
time += 1;
remaining -= speed;
totalRemaining -= speed;
}
overshoot = remaining;
});
return time;
}
Nov. 4, 2020
Comments: