Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 编程Pearls:查找具有最大和的子数组_Arrays_Algorithm - Fatal编程技术网

Arrays 编程Pearls:查找具有最大和的子数组

Arrays 编程Pearls:查找具有最大和的子数组,arrays,algorithm,Arrays,Algorithm,我在读编程珍珠的书,被困在某个地方。 查找具有最大和的子数组问题的最佳原始解决方案是: maxsofar = О maxendinghere = О for i = [0. n) { maxendinghere = max(maxendinghere + x[i], 0) maxsofar = max(maxsofar, maxendinghere) } 然后将问题更改如下,并要求修改程序: 我们必须找到和最接近零的子数组,而不是求和最大的子数组,而不是求和最小的子数组或

我在读编程珍珠的书,被困在某个地方。 查找具有最大和的子数组问题的最佳原始解决方案是:

maxsofar = О 
maxendinghere = О 
for i = [0. n) 
{
   maxendinghere = max(maxendinghere + x[i], 0) 
   maxsofar = max(maxsofar, maxendinghere) 
}
然后将问题更改如下,并要求修改程序:

我们必须找到和最接近零的子数组,而不是求和最大的子数组,而不是求和最小的子数组或其他数字f

所以我可以通过改变函数max来解决这个问题,这个函数将返回一个接近于零或f的数字。 maxsofar将被初始化为最接近零或f的元素 这个解决方案在上运行,但作者给出了一个困难的解决方案,并且运行在Onlogn中,并声称这是最佳解决方案,理论上是最好的

请您指出我的解决方案中的一个错误,如果书上说nlogn是最好的,那么我的解决方案肯定有一些错误

更新: 因此,我的答案是:

closest = get_element_closest_to_zero(); 
maxsofar = closest;
maxendinghere = 0; 
for i = [0. n) 
{
   maxendinghere = closest_to_zero(maxendinghere + x[i], closest);
   maxsofar = closest_to_zero(maxsofar, maxendinghere) ;
}

谢谢。

这里有一个反例

[100, 2, -2, -50]
正确答案是子数组[2,-2]。但是,由于100+2-2==100,100+2-2-50=50,50更接近于0,因此您的算法将返回[100,2,-2,-50]。

反例:[30;-50;45]

首先,您将选择30个。然后当你到达-50时,maxendinghere将是-20,maxsofar也将是-20。当到达45时,maxendinghere=closest-20+45=25,30=25,maxsofar将保持-20

然而,正确的答案是-5:-50+45=-5

那么序列[100,-201100]呢。这将给出初始条件

closest = 100
maxsofar = 100
maxendinghere = 0
一步之后

x[i] = 100
maxendinghere = closest_to_zero(100, 100)
maxsofar = 100
两步之后

x[i] = -201
maxendinghere = closest_to_zero(-101, 100)
maxsofar = 100
经过3步

x[i] = 100
maxendinghere = closest_to_zero(-101, 100)
maxsofar = 100

对于这个数组,您的算法将返回[1],但正确的响应应该是[100,-100]。

您介意清理伪代码吗?我认为你有一些拼写错误,比如maxCmaxendinghere.100+2-2和100+2-2-50永远不会相互比较。maxsofar初始化为2,然后最接近于0,maxendinghere将始终返回2,2-2情况除外。请查看我的上述更新。我遗漏了什么吗?啊,我很高兴你澄清了你的代码。你的问题的第一个版本是关于f的模棱两可的,但无论如何我都应该弄明白。我的错,你是对的。用我的解决方案来概括这个问题是,接近于零与最大不具有相同的属性,而这个属性与行maxmaxendinghere+x[i],0有关。不过,我现在还不能在午夜的时候,正式确定自己是马克斯。谢谢你指出。@Azho KG:嗯,100+-201+100是1,所以100的答案是不正确的。你是对的。太晚了,我困了,所以没抓住重点。
[1, 100, -100]