Categories
interview

In-Flight Media

// In-Flight Media

const getMovies = (flightDuration, movieDurations) => {
  const movieTargetDuration = flightDuration - 30;
  const requiredDurations = {};
  var ret = [];
  for (let [key, movieDuration] of Object.entries(movieDurations)) {
    if (movieDuration in requiredDurations) {
      // Found a pair.
      ret.push([requiredDurations[movieDuration], parseInt(key)]);
    }
    requiredDurations[movieTargetDuration - movieDuration] = parseInt(key);
  }

  // Find the pair with the maximum duration movie.
  var maxDuration = -1;
  var maxLoc = -1;
  for (let [key, value] of Object.entries(ret)) {
    var currMax = Math.max(movieDurations[value[0]], movieDurations[value[1]]);
    if (currMax > maxDuration) {
      maxDuration = currMax;
      maxLoc = key;
    }
  }
 
  // If no pair found then return [-1, 1].
  return maxLoc > -1 ? ret[maxLoc] : [-1, 1];
};

console.log(getMovies(90, [1, 10, 25, 35, 60])); // [2,3]

Demo