upd
This commit is contained in:
1
algorithms/labs/lab7/leetcode/3/link.txt
Normal file
1
algorithms/labs/lab7/leetcode/3/link.txt
Normal file
@@ -0,0 +1 @@
|
||||
https://leetcode.com/problems/create-maximum-number/?envType=problem-list-v2&envId=greedy
|
||||
46
algorithms/labs/lab7/leetcode/3/solution.py
Normal file
46
algorithms/labs/lab7/leetcode/3/solution.py
Normal file
@@ -0,0 +1,46 @@
|
||||
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
|
||||
Reference in New Issue
Block a user