【问题标题】:How to get the numbers/indexes used to find the maximum sum of an array elements when no two elements are adjacent当没有两个元素相邻时,如何获取用于查找数组元素的最大和的数字/索引
【发布时间】:2019-05-20 14:26:33
【问题描述】:

我发现下面提到的这些文章对于在没有两个元素相邻时找到数组元素的最大总和很有用。 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、4 个索引?非常感谢任何类型的帮助。

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

【问题讨论】:

  • 我的帖子内容丰富吗?有帮助吗?这个问题还在等待中……

标签: arrays algorithm


【解决方案1】:

正如您分享的问题中所说:定义数组M where 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多