查找遵守特定规则的最大非连续子数组

Find maximum non contiguous subarray that respect a specific rule

给定这两个数组:

[5, 3, 4, 1, 2]

[1, 3, 2, 4, 5]

求两个数组中元素索引为新月顺序的最大子序列:

示例:[3, 4] 这是一个答案,因为两个数组中的索引都是新月形的。 (与 [1, 2] 相同)。因此,答案 [3, 4, 1] 的子序列是错误的,因为索引在第一个数组中是新月,而在第二个数组中不是。

程序的输出应该是最大非连续子数组的长度。

这是我为解决这个问题而写的代码,但它只需要第一个子数组,我很难生成其他可能性

vector<pair<int, double>> esq;
vector<pair<int, double>> dir;
// N is the size of esq and dir
// pair<int, double> where int is the key (show in the example array) and double is the value, used for sort previously.
int cont = 1;
for (int i = 0; i < N - 1; i++)
{
    int cont_aux = 1;
    pair<int, double> pivot = esq[i];
    auto it_dir = find_if(dir.begin(), dir.end(), [&pivot](const pair<int, double> &p) { return p.first == pivot.first; });
    int last_index = it_dir - dir.begin();

    for (int j = 0; j < N; j++)
    {
        pair<int, double> actual = esq[j];
        auto it = find_if(dir.begin(), dir.end(), [&actual](const pair<int, double> &p) { return p.first == actual.first; });
        int pos = it - dir.begin();

        if (pos >= last_index) {
            last_index = pos;
            cont_aux++;
        }
    }

    cont = max(cont, cont_aux);
}

cout << cont << endl;
lista_test = [5,3, 4,1,7, 2]
lista2_test = [5,1,3, 2, 4,7]

def max_nocontigoous(list_a,list_b):
    #lets suppose that the list is ordered.
    count_i = 0
    count_j_previous = 0
    count_j = 0 
    counter_exclusive = 0
    listDouble = list()
    indice_real = 0
    for i in range(len(list_a)):
        try:
            element_a = list_a[i]
            if element_a in list_b and list_b.index(element_a)>=count_j:
                if count_j_previous != count_j:
                    listDouble[len(listDouble)-1].append(element_a)
                    count_j_previous = count_j
                else:
                    if(i == 0):
                        count_j_previous  -= 1
                    listDouble.append([element_a])
            else:
                listDouble.append([element_a])
                count_j_previous = count_j
                count_j = list_b.index(element_a)   
        except IndexError:
            print("Error in: " +str(i) + " iteration")
    return listDouble

print(max_nocontigoous(lista_test,lista2_test))

请注意,在我的例子中,我认为第一个数组或列表只能是一个列表,其值是有序且连续的。我刚刚考虑过它,因为我按照你的例子,你有一个数组,其中的值是连续排序的,而下一个数组不一定是连续的。 好看!