File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
3776-minimum-moves-to-balance-circular-array Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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 ))
You can’t perform that action at this time.
0 commit comments