알고리즘 75 - Number of People in the Bus

jabae·2021년 11월 1일
0

알고리즘

목록 보기
75/97

Q.

There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer pairs. Elements of each pair represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.

A)

var number = function(busStops){
  return busStops.map(el => el[0] - el[1]).reduce((sum, cur) => sum + cur, 0);
}

other

오호... 이렇게 바로 .reduce((rem, [on, off]) => ...) 안에 누적될 반환값과 배열을 선언하는 게 가능하다! 😱

const number = (busStops) => busStops.reduce((rem, [on, off]) => rem + on - off, 0);
profile
it's me!:)

0개의 댓글