본문 바로가기

Algorithm/Brute Force

(Python3) - LeetCode (Medium) : 1769. Minimum Number of Operations to Move All Balls to Each Box.py

반응형

https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box

전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 배열 answer을 선언 후 빈 배열로 초기화합니다.

📔 풀이과정

i번째 box로 옮기기 위해 j번째 box에 대해 for loop를 수행하며 다음을 진행합니다.

 

1. 필요 연산 수 op를 선언 후 0으로 초기화합니다. 

 

2. j번째 box가 1이라면 이를 i번째로 옮기기 위해 abs(i-j)만큼의 연산이 필요하므로 op에 해당 값들을 누적합니다.

 

3. answer에 i번째로 옮길 때의 최소 연산 수 op를 append해줍니다.

📔 정답 출력 | 반환

answer를 반환합니다.


📕 Code

📔 Python3

class Solution:
    def minOperations(self, boxes: str) -> List[int]:
        answer = []

        for i, box in enumerate(boxes):
            op = 0

            for j, box in enumerate(boxes):
                if box == '1':
                    op += abs(i-j)
            answer.append(op)

        return answer

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.