T1财富评估项目
求数组和取最大值
from typing import List
def solution(financials: List[List[int]]) -> int:
return max([sum(num) for num in financials])
T2礼物价值
排序,贪心
from typing import List
def solution(giftPackages: List[List[int]], eventCapacity: int) -> int:
ans = 0
q, k = sorted(giftPackages, key=lambda x:x[1]), eventCapacity
i = 0
while k > 0 and i < len(q):
ans += q[i][0] * q[i][1] if q[i][0] <= k else k * q[i][1]
k = 0 if q[i][0] >= k else k - q[i][0]
i += 1
return ans
T3最优远足问题
二分 + bfs搜索(直接套最短路径模版就行)
from typing import List
from collections import deque
def check(a, k):
n, m = len(a), len(a[0])
bfs = [[False] * m for _ in range(n)]
queue = deque([(0, 0)])
bfs[0][0] = True
while queue:
x, y = queue.popleft()
if x == n - 1 and y == m - 1:
return True
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m and not bfs[nx][ny] and abs(a[nx][ny] - a[x][y]) <= k:
bfs[nx][ny] = True
queue.append((nx, ny))
return False
def solution(heights: List[List[int]]) -> int:
n, m = len(heights), len(heights[0])
low, high = min((min(row) for row in heights)), max((max(row) for row in heights))
while low < high:
mid = (low + high) // 2
if check(heights, mid):
high = mid
else:
low = mid + 1
return low
T4画作
from typing import List
MOD = 10 ** 9 + 7
def solution(n: int, k: int) -> int:
f = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
for j in range(1, min(i, k) + 1):
f[i][j] = (f[i - 1][j - 1] + f[i - 1][j] * (i - 1)) % MOD
return f[n][k]