class Solution:
def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
ans = [0,0]
for x,y in dimensions:
ans = max(ans,[x*x+y*y,x*y])
return ans[1]
贪心讨论怎么想都很难,数据量很小,干脆BFS。
DIRS1 = [(0,1),(0,-1),(1,0),(-1,0)]
DIRS2 = [(1,1),(1,-1),(-1,1),(-1,-1)]
class Solution:
def minMovesToCaptureTheQueen(self, a: int, b: int, c: int, d: int, e: int, f: int) -> int:
a -= 1
b-=1
c-=1
d-=1
e-=1
f-=1
q = [(a,b,c,d)]
vis = set(q)
ans = 1
while q:
nq = []
for a,b,c,d in q:
for dx,dy in DIRS1:
cnt = 0
while True:
cnt += 1
x,y = a+dx*cnt,b+dy*cnt
if not (0<=x<8 and 0<=y<8) or x == c and y == d:
break
if x == e and y == f:
return ans
v = (x,y,c,d)
if v not in vis:
vis.add(v)
nq.append(v)
for dx,dy in DIRS2:
cnt = 0
while True:
cnt += 1
x,y = c+dx*cnt,d+dy*cnt
if not (0<=x<8 and 0<=y<8) or x == a and y == b:
break
if x == e and y == f:
return ans
v = (a,b,x,y)
if v not in vis:
vis.add(v)
nq.append(v)
ans += 1
q = nq
class Solution:
def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int:
h = len(nums1)//2
n = len(nums1)
a,b = set(nums1),set(nums2)
x,y,z = len(a-b),len(b-a),len(a&b)
ans = min(h,x)+min(h,y)
ans += min(n-ans,z)
return ans
class Solution:
def maxPartitionsAfterOperations(self, s: str, k: int) -> int:
n = len(s)
if k == 26: # k是26怎么改都是1组
return 1
if k > len(set(s)): # 一共k-1个不同字符,怎么改最多也只有k种字符
return 1
if k == 1:
f = [1]*n
for i in range(1,n):
if s[i] == s[i-1]:
f[i] += f[i-1]
ans = f.count(1)
mx = max(f)
if mx >= 3:
return ans + 2
if mx == 2:
return ans + 1
return ans
s += '*'
@cache
def f(i,chance,start):
if i == n:
return 0
vis = {start}
ans = 1
for j in range(i+1,n):
vis.add(s[j])
c = s[j+1]
if chance and c not in vis and len(vis) == k - 1 and j-i+1>=k:
ans = max(ans, 1 + f(j+1,0,c))
if chance and len(vis) == k and c in vis:
for z in range(26):
d = chr(ord('a')+z)
if d not in vis:
ans = max(ans, 1 + f(j+1,0,d))
if len(vis) == k and c not in vis:
ans = max(ans, 1 + f(j+1,chance,c))
break
return ans
return f(0,1,s[0])