没有两个元素相邻时如何获取用于查找数组元素的最大和的数字/索引

时间:2019-05-19 12:57:21

标签: arrays algorithm

我发现以下提到的这些文章对于在没有两个相邻元素的情况下找到数组元素的最大和很有用。 Maximum sum of non consecutive elements https://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/

但是我无法理解背后的逻辑,即如何获得用于查找最大和的数字。例如:

array => {2, 5, 10, 1, 10}

通过使用2、10和10,最大总和将为22,现在如何查找大数组时使用的数字/索引。在此示例中,如何找到我已使用数组的2,10,10或0,2,4th个索引?非常感谢任何帮助。

Maximum sum of non consecutive elements https://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/

1 个答案:

答案 0 :(得分:0)

正如您在问题中所说的:定义数组M,其中M[i] = max(M(i - 1), M(i - 2) + A[i]) for i = 1, ..., n

此外,创建数组I,其中将包含所选索引。

首先通过选择M的前2个元素(避免边缘情况)来初始化所有内容:

A = 2, 5, 10, 1, 10 // input array

M = [A[0]]; // index 0 of M is only first element
I = []; // init empty index array
if (A[0] > A[1]) { // if first element bigger
    M[1] = A[0]; //choose him for second place also
    I = [true, false]; // set first two indexs as taking the first element in A and not the second
} else { // the second element is bigger
    M[1] = A[1]; // assign him to M
    I = [false, true] //set I for not taking the first element but the second one
}

现在在所有A数组上循环为:

for i 2 to cnt(A)-1 {
    if (M[i-1] > M[i-2] + A[i]) { // if prefer to take last place
        M[i] = M[i-1]; // set current max at i
        I[i] = false; // we don't take the current places
    } else {
        M[i] = M[i-2] + A[i]; // set current max at i
        I[i] = true; I[i-1] = false, I[i-2] = true; //change older value as decided to take this path
    }
}

以您为例:

A = 2, 5, 10, 1, 10
M = 2, 5, 12, 12, 22
I = T, F, T, F, T
相关问题