일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Python
- codeup
- 투포인터
- LeetCode
- 파이썬
- two-pointer
- 자연어처리
- 릿코드
- 파이썬알고리즘
- 슬라이딩윈도우
- Python3
- 생성형AI
- gcp
- Greedy
- 알고리즘
- slidingwindow
- 파이썬기초100제
- array
- nlp
- heap
- Stack
- 니트코드
- SQL
- 코드업
- stratascratch
- GenerativeAI
- sql코테
- dfs
- 리트코드
- GenAI
Archives
- Today
- Total
Tech for good
[Leetcode/Array, Greedy, Sorting] 2037. Minimum Number of Moves to Seat Everyone 본문
IT/Computer Science
[Leetcode/Array, Greedy, Sorting] 2037. Minimum Number of Moves to Seat Everyone
Diana Kang 2025. 5. 26. 22:42class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
students.sort(reverse=True)
seats.sort(reverse=True)
minMove = 0
for i in range(len(students)):
minMove += abs(students[i] - seats[i])
return minMove
✅ Why Use abs() (Absolute Value)?
The problem asks for the total number of moves to align each student with a seat.
Each move increases or decreases a student's position by 1 unit, so the number of moves between:
- a student at position 3
- and a seat at position 7
...is 4 (7 - 3 = 4).
But if the student is at position 7 and the seat is at 3, then:
- 3 - 7 = -4, but moves can't be negative.
- So we take abs(3 - 7) → 4 moves.
❓ Why does the minMove we calculate using abs(seats[i] - students[i]) actually give the minimum total number of moves?
✅ Because we're using a greedy strategy with sorting.
Step-by-step logic:
- Sort both seats and students arrays.
- We pair the smallest available seat with the smallest-positioned student,
- the second smallest seat with the second smallest student,
- and so on...
- Example
seats = [1, 3, 7]
students = [2, 6, 5]
# Sorted:
seats = [1, 3, 7]
students = [2, 5, 6]
# Matching:
abs(1 - 2) = 1
abs(3 - 5) = 2
abs(7 - 6) = 1
Total = 4 moves (minimum)
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/DFS, BFS, Matrix] 733. Flood Fill (0) | 2025.05.28 |
---|---|
[Leetcode/Array, Greedy, Sorting] 1403. Minimum Subsequence in Non-Increasing Order (0) | 2025.05.27 |
[Leetcode/Greedy] 1903. Largest Odd Number in String (0) | 2025.05.24 |
[Leetcode/Array, Greedy, Sorting] 1710. Maximum Units on a Truck (0) | 2025.05.23 |
[Leetcode/Greedy] 1323. Maximum 69 Number (0) | 2025.05.23 |