File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Time: O(nlogn)
2
+ # Space: O(n)
3
+
4
+ from sortedcontainers import SortedList
5
+
6
+
7
+ # simulation, doubly linked list, sorted list
8
+ class Solution (object ):
9
+ def minimumPairRemoval (self , nums ):
10
+ """
11
+ :type nums: List[int]
12
+ :rtype: int
13
+ """
14
+ def add (i ):
15
+ if 0 <= i < right [i ] < len (nums ):
16
+ sl .add ([nums [i ]+ nums [right [i ]], i ])
17
+ if nums [i ] > nums [right [i ]]:
18
+ cnt [0 ] += 1
19
+
20
+ def remove (i ):
21
+ if 0 <= i < right [i ] < len (nums ):
22
+ sl .remove ([nums [i ]+ nums [right [i ]], i ])
23
+ if nums [i ] > nums [right [i ]]:
24
+ cnt [0 ] -= 1
25
+
26
+ left = range (- 1 , (len (nums )+ 1 )- 1 )
27
+ right = range (1 , len (nums )+ 1 )
28
+ cnt = [sum (nums [i ] > nums [i + 1 ] for i in xrange (len (nums )- 1 ))]
29
+ sl = SortedList ([nums [i ]+ nums [i + 1 ], i ] for i in xrange (len (nums )- 1 ))
30
+ result = 0
31
+ while cnt [0 ]:
32
+ _ , i = sl [0 ]
33
+ remove (left [i ])
34
+ remove (i )
35
+ remove (right [i ])
36
+ nums [i ] += nums [right [i ]]
37
+ left [right [right [i ]]] = i
38
+ right [i ] = right [right [i ]]
39
+ add (left [i ])
40
+ add (i )
41
+ result += 1
42
+ return result
You can’t perform that action at this time.
0 commit comments