计算最小不公平金额

I am trying to solve a hackerRank problem called angry children 2, but getting Errors. I don't know what is wrong with my code. I am getting 'abort called' error, and also 'code could not be executed within time' error. Some are showing wrong answer. Whereas 3 tests are successful. Here is the link to the problem as the problem is very difficult to explain: HackerRank

这是我尝试过的:

function angryChildren(k, packets) {
  //sorting from lower to higher value
  let arr = packets.sort((a, b) => a - b)
  //getting the required values only
  arr = arr.slice(0, k)
  let req = arr.map((v, i) => arr.slice(i + 1).map(w => [v, w]))

  let newArr = []
  for (let i = 0; i < req.length - 1; i++) {
    newArr = newArr.concat(req[i]);
  }
  let ans = newArr.map(a => Math.abs(a[0] - a[1])).reduce((a, b) => a + b)
  return ans
}
评论