Files
exams/algorithms/labs/lab7/leetcode/3/solution.py
2025-10-01 22:55:09 +03:00

47 lines
1.4 KiB
Python

from typing import List
class Solution:
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
def pick(arr: List[int], t: int) -> List[int]:
drop = len(arr) - t
st = []
for x in arr:
while drop and st and st[-1] < x:
st.pop()
drop -= 1
st.append(x)
return st[:t]
def greater(a: List[int], i: int, b: List[int], j: int) -> bool:
while i < len(a) and j < len(b) and a[i] == b[j]:
i += 1
j += 1
if j == len(b):
return True
if i < len(a) and a[i] > b[j]:
return True
return False
def merge(a: List[int], b: List[int]) -> List[int]:
i = j = 0
res = []
while i < len(a) or j < len(b):
if greater(a, i, b, j):
res.append(a[i])
i += 1
else:
res.append(b[j])
j += 1
return res
m, n = len(nums1), len(nums2)
ans = []
for i in range(max(0, k - n), min(k, m) + 1):
a = pick(nums1, i)
b = pick(nums2, k - i)
cand = merge(a, b)
if not ans or cand > ans:
ans = cand
return ans