JSFiddle - React, Tailwind, and code Playground
by Alexander Branchugov
JavaScript
function getTotalTime(heroes, n) {
if (n === 1) {
return heroes.reduce((totalTime, timeOfRound) =>
totalTime + timeOfRound, 0
);
}
let timeOfFirstHero = heroes.shift() || 0;
let timeOfSecondHero = heroes.shift() || 0;
let totalBattleTime = Math.max(timeOfFirstHero, timeOfSecondHero);
while(heroes.length > 0) {
const timeOfRound = heroes.shift();
if (timeOfFirstHero <= totalBattleTime) {
timeOfFirstHero += timeOfRound;
} else {
timeOfSecondHero += timeOfRound;
}
totalBattleTime = Math.max(timeOfFirstHero, timeOfSecondHero);
}
return totalBattleTime;
}
console.log(getTotalTime([3, 5, 10], 2))