구현문제였지만 상당히 복잡하였다. maxFloor와 minFloor를 어떻게 효율적으로 찾고 둘을 비교할지가 관건이었다.
T = 10
for tc in range(1, T+1):
N = int(input())
arr = list(map(int, input().split()))
cnt = 0
maxNum = reduce(lambda a, b: a if a > b else b, arr)
minNum = reduce(lambda a, b: a if a < b else b, arr)
while True:
minIndex = []
maxIndex = []
for i in range(100):
if maxNum == arr[i]:
maxIndex.append(i)
if minNum == arr[i]:
minIndex.append(i)
if not len(maxIndex) > 0:
maxNum -= 1
continue
if not len(minIndex) > 0:
minNum += 1
continue
maxFloor = arr[maxIndex[len(maxIndex)-1]]
minFloor = arr[minIndex[len(minIndex)-1]]
minLength = len(maxIndex) if len(maxIndex) <= len(minIndex) else len(minIndex)
if cnt + minLength > N or maxNum == minNum:
result = maxFloor - minFloor
break
if len(maxIndex) > len(minIndex):
for j in range(minLength):
arr[maxIndex[j]] -= 1
arr[minIndex[j]] += 1
cnt += 1
minNum += 1
continue
if len(maxIndex) < len(minIndex):
for j in range(minLength):
arr[maxIndex[j]] -= 1
arr[minIndex[j]] += 1
cnt += 1
maxNum -= 1
continue
else:
for j in range(minLength):
arr[maxIndex[j]] -= 1
arr[minIndex[j]] += 1
cnt += 1
maxNum -= 1
minNum += 1
continue
print(f"#{tc} {result}")
출처
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV139KOaABgCFAYh