java - Kadane 的算法中是否保留了足够的信息来返回实际的最大子数组或索引,而不仅仅是求和?

标签 java algorithm

这是 Kadane 算法的 Java 实现,用于查找具有最大和的连续子数组的和。

    static int maxSum(int[] arr) {
        int maxEndingHere = arr[0];
        int maxGlobal = arr[0];

        for (int i = 1; i < arr.length; i++) {
            maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
            maxGlobal = Math.max(maxGlobal, maxEndingHere);
        }
        return maxGlobal;

    }

这只是返回总和。我想要实际的子阵列。不过,似乎信息丢失了。我尝试在局部最大值重置时更新起始索引,在全局最大值更新时更新结束索引,但在这种情况下失败了:

        int[] arr = {-57, -10000, -1, -4, -45, -6, -9, -19, -16, -17};

注意这里有一个类似的问题:How to return maximum sub array in Kadane's algorithm?

但据我所知,在总和为负的情况下,每个答案都会失败。

最佳答案

既然你标记了algorithm,这里是一个解释,然后是一个python实现。

此问题是 Kadane 算法的直接扩展。 Kadane的算法如下:

for each item in arr:
    current_max = max(current_max + item, item)
    global_max = global_max(current_max, global_max)

我们只需要记录当前和全局最大值更新时的索引:

for each item in arr:

    # updating current max and keeping track current of start and end indices
    current_max = max(current_max + item, item)
    if item is new current_max: set current_start_index to this index
    set current_end_index to this index

    # keep track of global start and end indices
    global_max = max(global_max, current_max)
    if global_max has been updated: 
        set global_start to current_start
        set global_end to current_end

Python 实现:

def maxSum(arr):

  cur_max = glob_max = float('-inf')
  glob_start = glob_end = cur_start = -1

  for index, item in enumerate(arr):

    if item > cur_max + item:
      cur_max = item
      cur_start = index
    else:
      cur_max += item

    if cur_max > glob_max:
      glob_max = cur_max
      glob_start = cur_start
      glob_end = index
  return arr[glob_start:glob_end+1]

一些测试用例:

arr = [-57, -10000, -1, -4, -45, -6, -9, -19, -16, -17]
arr = [-1, 2, -1, 20, -4, -5, -6, -9, -19, -16, -17]

输出:

[-1]
[2, -1, 20]

请注意,如果您想考虑空的连续子数组,只需在末尾添加一个检查 - 如果全局最大值小于 0,则返回一个空数组。

最后一些额外的代码来证明算法是正确的:

def kadane(arr):
  a = b = float('-inf')
  for i in arr:
    a = max(i, a+i)
    b = max(a, b)

  return b

from random import random

for _ in range(10000):
  arr = [random()-0.5 for _ in range(50)]
  assert kadane(arr) == sum(maxSum(arr))

这将创建具有正数和负数的随机数组,并断言输出数组的总和等于 kadane 算法的常规版本的输出。

repl.it link with code

关于java - Kadane 的算法中是否保留了足够的信息来返回实际的最大子数组或索引,而不仅仅是求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526700/

相关文章:

algorithm - 一个版本的熄灯游戏的可解性

java - Spring MVC : POST and PUT not working

java - 修复 Eclipse 中的问题

java - 避免 BigDecimal 添加 0 java

algorithm - float 的精确和

计算无向线段平均方向的算法

algorithm - 电话号码关键数字/字母排列

java - 如何将我的电话应用程序包含在 'open with' 列表中?

java - Hibernate vs JPA vs JDO - 各自的优缺点?

java - 条件空对象 : Comparison method violates its general contract