java - 需要最大子数组提示

标签 java algorithm

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.

我无法解决这个问题,但我只是想得到一些提示。

它说这可以使用动态规划来解决,但我很难看到其中的联系。

DP 连接会获取整个 数组的总和吗?

最佳答案

可以找到您的问题的引用 here .

你必须使用 Kadane 的算法来解决这种情况,它是这样的:

Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
    (a) max_ending_here = max_ending_here + a[i]
    (b) if(max_ending_here < 0)
        max_ending_here = 0
    (c) if(max_so_far < max_ending_here)
        max_so_far = max_ending_here
    return max_so_far

供您引用的示例代码:

static int maxSubArraySum(int a[])
{
    int size = a.length;
    int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;

    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}

关于java - 需要最大子数组提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406965/

相关文章:

java - PMD 规则 : How to properly solve this DD-anomaly issue

java - 有没有办法在谷歌驱动器文件的属性中搜索?

java - 如何在Reactor中进行分页?

c++ - 为什么 std::copy 或 std::swap 不需要 <algorithm>?

arrays - 如何计算多维数组中的反转?

java - Jackson @JsonTypeInfo property 属性采用字符串值

java - 在Java中的单个服务器-多个客户端中,消息不会从服务器发送到客户端

algorithm - 如何使用经过 10 个参数训练的人工神经网络对具有 3 个参数的实例进行分类?

arrays - 查找 2 个巨大数组之间的变化

algorithm - 哈希是否最适合要求高查找速度的应用程序?