Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 30x 13x 13x 30x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 17x 17x 17x 17x 89x 89x 17x 17x 17x 3x 3x 3x 1x 1x | // There is a row of empty (.) and filled(x) seats.
// Find the minimum number of moves required to make the people sit together.
// • Constraints
// • 1 < N < 1e6
import sumNumbers from "../../utils/sumNumbers";
// Example:
// Input: "..x..x."
// Output: 2
//
// Explanation:
// Either of the "×"s can move to the seat closest to the other one.
// "..xx..." OR "....xx."
const moveSeats = (seats: string): number => {
const listSeat = seats.split("");
const seatHavePeople = listSeat.reduce<number[]>((acc, curr, index) => {
if (curr === "x") {
acc.push(index);
}
return acc;
}, []);
// return 0 if no people
if (!seatHavePeople.length) return 0;
// move it to in a row
const seatHavePeopleRow = seatHavePeople.map((item, index) => item - index);
const pivot = seatHavePeopleRow[Math.floor(seatHavePeopleRow.length / 2)];
let result;
for (let x = pivot; x < seats.length; x++) {
let total = 0;
// loop to seatHavePeopleRow
for (const seat of seatHavePeopleRow) {
total += Math.abs(seat - x);
}
result = result ? Math.min(result, total) : total;
}
return result || 0;
};
export default moveSeats;
|