-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMakeArrayStrictlyIncreasing.py
63 lines (50 loc) · 1.87 KB
/
MakeArrayStrictlyIncreasing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- coding: utf-8 -*-
# @File : MakeArrayStrictlyIncreasing.py
# @Date : 2020-08-20
# @Author : tc
"""
题号 1187. 使数组严格递增
给你两个整数数组 arr1 和 arr2,返回使 arr1 严格递增所需要的最小「操作」数(可能为 0)。
每一步「操作」中,你可以分别从 arr1 和 arr2 中各选出一个索引,分别为 i 和 j,0 <= i < arr1.length 和 0 <= j < arr2.length,然后进行赋值运算 arr1[i] = arr2[j]。
如果无法让 arr1 严格递增,请返回 -1。
示例 1:
输入:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
输出:1
解释:用 2 来替换 5,之后 arr1 = [1, 2, 3, 6, 7]。
示例 2:
输入:arr1 = [1,5,3,6,7], arr2 = [4,3,1]
输出:2
解释:用 3 来替换 5,然后用 4 来替换 3,得到 arr1 = [1, 3, 4, 6, 7]。
示例 3:
输入:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
输出:-1
解释:无法使 arr1 严格递增。
提示:
1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9
参考:https://leetcode.com/problems/make-array-strictly-increasing/discuss/377403/Python-DP-solution-with-explanation.
"""
from typing import List
import collections
import bisect
class Solution:
def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:
dp = {-1: 0}
arr2.sort()
for i in arr1:
tmp = collections.defaultdict(lambda: float('inf'))
for key in dp:
if i > key:
tmp[i] = min(tmp[i], dp[key])
loc = bisect.bisect_right(arr2, key)
if loc < len(arr2):
tmp[arr2[loc]] = min(tmp[arr2[loc]], dp[key] + 1)
dp = tmp
if dp:
return min(dp.values())
return -1
if __name__ == '__main__':
arr1 = [1,5,3,6,7]
arr2 = [4,3,1]
solution = Solution()
print(solution.makeArrayIncreasing(arr1,arr2))