【问题标题】:Maximum contigous subsequence sum of x elementsx 个元素的最大连续子序列和
【发布时间】:2015-10-31 14:24:09
【问题描述】:

所以我想出了一个问题,我已经查看和搜索但没有找到答案...获得最大连续子序列的最佳(并且说最好,我的意思是最快)方法是什么x 个元素的总和

假设我有:A[] = {2, 4, 1, 10, 40, 50, 22, 1, 24, 12, 40, 11, ...}。 然后我问:

"What is the maximum contigous subsequence on array A with 3 elements?"

请在一个包含超过 100000 个元素的数组中想象一下...有人可以帮帮我吗?

感谢您的宝贵时间和您的帮助!

【问题讨论】:

    标签: sum max elements subsequence contiguous


    【解决方案1】:

    我用谷歌搜索了一下,发现this

    使用分而治之的方法,我们可以在 O(nLogn) 时间内找到最大子数组和。以下是分治算法。

    这个问题的 Kadane 算法需要 O(n) 时间。因此,Kadane 的算法优于分治法

    the code:

    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
    

    【讨论】:

    • 这不是我真正想要的,因为我需要按 X 元素分组的最大总和......想象在上面的示例中,最大总和是所有元素,因为它们都是正数,但我想要由 3 个元素分组的最大总和......所以:它将是 40 50 22。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2011-05-28
    • 2015-10-31
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多