## AMD Interview Question

Students**Country:**India

**Interview Type:**Written Test

c++, recursion, O(2 ^ n)

```
#include <iostream>
#include <vector>
using namespace std;
bool nonDecreasingSequence(vector<int>& a, vector<int>& b, vector<int>&c, int idx, int bit) {
if (idx == a.size()) {
return bit == 3;
}
if (idx == 0 || a[idx] >= c[idx - 1]) {
c[idx] = a[idx];
if (nonDecreasingSequence(a, b, c, idx + 1, bit | 1) == true) return true;
}
if (idx == 0 || b[idx] >= c[idx - 1]) {
c[idx] = b[idx];
if (nonDecreasingSequence(a, b, c, idx + 1, bit | 2) == true) return true;
}
return false;
}
int main(int argc, char* argv[]) {
vector<int> a, b, c;
int t, n, i;
cin >> t;
while (t--) {
cin >> n;
a.assign(n, 0);
b.assign(n, 0);
c.assign(n, 0);
for (i = 0; i < n; i++) cin >> a[i];
for (i = 0; i < n; i++) cin >> b[i];
if (nonDecreasingSequence(a, b, c, 0, 0) == true) {
for (i = 0; i < n; i++) {
cout << c[i] << " ";
}
cout << "\n";
} else {
cout << "IMPOSSIBLE\n";
}
}
return 0;
}
```

Stating this as optimization problem: Find max non decreasing sequence so that each species contributes at least one element. If max length is equal to length of species, answer to original question is TRUE.

Trying to solve this as simple DP might yield false positive results when all elements are taken from only one of the species, e.g. {{2,2,3,3},{4,1,1,1}}, to avoid this we will induce fake obstacles, a different pair of indexes from species A an B. This will force DP to make a switch at least once.

Overall complexity will be O(n^3).

- blckembr December 16, 2015