# A. Sort Even and Odd Indices Independently (opens new window)
Partition array A
, sort the even indexes by ascending order and odd indexes by descending order.
DETAILS
def sortEvenOdd(self, A):
A[::2], A[1::2] = sorted(A[::2]), sorted(A[1::2])[::-1]
return A
# B. Smallest Value of the Rearranged Number (opens new window)
- If
num = 0
, return0
. - If
num > 0
, sort all digits ofnum
, switch the first0
with the smallest non-zero digits. For example:000123
to100023
. - If
num < 0
, sort all digits ofnum
by descending order, add minus sign. For example,-40123
to-43210
.
DETAILS
def smallestNumber(self, num: int) -> int:
if num == 0: return 0
pos = num > 0
A = list(str(abs(num)))
n = len(A)
if pos:
A.sort()
idx = 0
while idx < n and A[idx] == '0':
idx += 1
A[0], A[idx] = A[idx], A[0]
else:
A.sort(reverse = True)
curr = int("".join(A))
return curr if pos else -curr
# 2166. Design Bitset (opens new window)
Implementation of some bitwise operations.
DETAILS
class Bitset:
def __init__(self, size: int):
self.size = size
self.n = 0
self.full = 1 << size
def fix(self, idx: int) -> None:
self.n |= 1 << (self.size - idx - 1)
def unfix(self, idx: int) -> None:
mask = 1 << (self.size - idx - 1)
self.n &= ~mask
def flip(self) -> None:
self.n ^= (self.full - 1)
def all(self) -> bool:
return self.n + 1 == self.full
def one(self) -> bool:
return self.n != 0
def count(self) -> int:
return self.n.bit_count()
def toString(self) -> str:
n = bin(self.n)[2:]
return "0" * (self.size - len(n)) + n
# 2167. Minimum Time to Remove All Cars Containing Illegal Goods (opens new window)
Please refer to This LC Discussion (opens new window) for my solutions in English.
Left-right DP.
DETAILS
def minimumTime(self, A: str) -> int:
n = len(A)
if n == 1: return 1 if A == '1' else 0
lft, rgt = [] * n, [] * n
curr = 0
for a in A:
if a == '1':
curr += 1
else:
curr -= 1
lft.append(curr)
curr = 0
for a in A[::-1]:
if a == '1':
curr += 1
else:
curr -= 1
rgt.append(curr)
rgt.reverse()
exp = 2 * A.count('1') # MaximumCost, that is the cost of removing all cars with a cost of 2.
lmax, curr = [lft[0]], lft[0]
for i in range(1, n):
curr = max(curr, lft[i])
lmax.append(curr)
rmax, curr = [rgt[-1]], rgt[-1]
for i in range(n - 2, -1, -1):
curr = max(curr, rgt[i])
rmax.append(curr)
rmax.reverse()
maxp = 0 # The maximum cost we can SAVE.
for i in range(n - 1):
maxp = max(maxp, max(0, lmax[i]) + max(0, rmax[i + 1]))
return exp - maxp # The overall cost is the MaximumCost - "the maximum cost we can save".