Skip to content

Commit f896d39

Browse files
committed
Time: 151 ms (100%), Space: 36.6 MB (0%) - LeetHub
1 parent 1d79894 commit f896d39

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# time complexity: O(nlogn)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def minMoves(self, balance: List[int]) -> int:
8+
n = len(balance)
9+
total = sum(balance)
10+
if total < 0:
11+
return -1
12+
negIdx = -1
13+
for i in range(n):
14+
if balance[i] < 0:
15+
negIdx = i
16+
break
17+
if negIdx == -1:
18+
return 0
19+
need = -balance[negIdx]
20+
donors = []
21+
for i in range(n):
22+
if i != negIdx and balance[i] > 0:
23+
dist = min((i - negIdx) % n, (negIdx - i) % n)
24+
donors.append((dist, balance[i]))
25+
donors.sort()
26+
moves = 0
27+
for dist, amount in donors:
28+
if need == 0:
29+
break
30+
take = min(need, amount)
31+
moves += take * dist
32+
need -= take
33+
return moves if need == 0 else -1
34+
35+
36+
balance = [5, 1, -4]
37+
print(Solution().minMoves(balance))
38+
balance = [1, 2, -5, 2]
39+
print(Solution().minMoves(balance))
40+
balance = [-3, 2]
41+
print(Solution().minMoves(balance))

0 commit comments

Comments
 (0)