-
Notifications
You must be signed in to change notification settings - Fork 17
/
minimum-replacements-to-sort-the-array.py
59 lines (43 loc) · 1.57 KB
/
minimum-replacements-to-sort-the-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from typing import List, Tuple
class Solution:
def minimumReplacement(self, nums: List[int]) -> int:
limit = nums[-1]
total_splits = 0
def optimal_split(num: int, limit: int) -> Tuple[int, int]:
if num % limit == 0:
return (limit, num // limit - 1)
else:
splits = num // limit
return (num // (splits + 1), splits)
for num in reversed(nums):
if num <= limit:
limit = num
else:
limit, splits = optimal_split(num, limit)
total_splits += splits
return total_splits
def minimumReplacementBruteForce(self, nums: List[int]) -> int:
limit = nums[-1]
total_splits = 0
def optimal_split(num: int, limit: int) -> Tuple[int, int]:
count = 0
divisor = limit
buffer = 0
while num % divisor != 0:
if divisor - (num % divisor) <= buffer:
num += divisor - (num % divisor)
buffer -= divisor - (num % divisor)
continue
count += num // divisor
num = num % divisor
buffer += count
divisor -= 1
count += num // divisor
return (divisor, count - 1)
for num in reversed(nums):
if num <= limit:
limit = num
else:
limit, splits = optimal_split(num, limit)
total_splits += splits
return total_splits