Skip to content

Commit 3ea8016

Browse files
authored
Update make-array-strictly-increasing.cpp
1 parent 76615c2 commit 3ea8016

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

C++/make-array-strictly-increasing.cpp

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,35 +4,33 @@
44
class Solution {
55
public:
66
int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2) {
7-
sort(arr2.begin(), arr2.end());
8-
unordered_map<int, int> dp = {{-1, 0}};
9-
for (const auto& i : arr1) {
7+
std::sort(arr2.begin(), arr2.end());
8+
arr2.erase(std::unique(arr2.begin(), arr2.end()), arr2.end());
9+
unordered_map<int, int> dp = {{0, arr1[0]}, {1, arr2[0]}};
10+
for (int i = 1; i < arr1.size(); ++i) {
1011
unordered_map<int, int> next_dp;
1112
for (const auto& [j, count] : dp) {
12-
if (i > j) {
13-
if (!next_dp.count(i)) {
14-
next_dp[i] = dp[j];
13+
if (dp[j] < arr1[i]) {
14+
if (!next_dp.count(j)) {
15+
next_dp[j] = arr1[i];
1516
} else {
16-
next_dp[i] = min(next_dp[i], dp[j]);
17+
next_dp[j] = min(next_dp[j], arr1[i]);
1718
}
1819
}
19-
const auto& it = upper_bound(arr2.cbegin(), arr2.cend(), j);
20+
const auto& it = upper_bound(arr2.cbegin(), arr2.cend(), dp[j]);
2021
if (it != arr2.cend()) {
21-
if (!next_dp.count(*it)) {
22-
next_dp[*it] = dp[j] + 1;
22+
if (!next_dp.count(j + 1)) {
23+
next_dp[j + 1] = *it;
2324
} else {
24-
next_dp[*it] = min(next_dp[*it], dp[j] + 1);
25+
next_dp[j + 1] = min(next_dp[j + 1], *it);
2526
}
2627
}
2728
}
2829
dp = move(next_dp);
2930
}
30-
if (!dp.empty()) {
31-
return min_element(dp.cbegin(), dp.cend(),
32-
[](const auto& a, const auto& b) {
33-
return a.second < b.second;
34-
})->second;
31+
if (dp.empty()) {
32+
return -1;
3533
}
36-
return -1;
34+
return min_element(dp.cbegin(), dp.cend())->first;
3735
}
3836
};

0 commit comments

Comments
 (0)