最大连续子数组和

huangapple go评论60阅读模式
英文:

Max contiguous subarray sum

问题

所以,我刚刚参加了一个在线编程评估,其中我得到了两个问题,其中一个是关于连续子数组和的问题,提供了2个复杂的编程问题+8个多项选择题,需要在1小时内完成。

这里我将讨论上面提到的最大连续子数组和的问题。通常我发现困难的部分是处理负数以及连续性。我的做法是首先对给定的数组应用Collection.sort(arr),然后我再根据它们的绝对值对负值进行排序,例如对于i.. arr.get(i)! =abs(arr.get(i)),对于j.. 如果arr.get(i)>arr.get(j),则交换,最终数组为-1,-2,3,4,5,例如对于给定的随机数数组,我在每个i之后以及所有的j迭代中保持一个最大值,我有如果max<sum(即sum+arr.get(allj)+arr(particular i)),则max=sum。所以这样可以给我最大的和,但是在14个案例中我只通过了4个,我认为原因是排序后的数组并不总是连续的,所以有什么建议可以在这个逻辑中加入连续性的概念,以使其适用于所有情况。

英文:

So, i just had an online programming assessment where i was given 2 problems one of which was this contiguous subarray sum provided 2 Complex coding questions + 8 mcqs and was to be completed in 1 hr.

Here i would be discussing one of the above mentioned max contiguous sum of subarray. Usually the tough part i find was handling negative numbers and contiguously. What i did was i first applied a Collection.sort(arr) to the given array and i again sorted the negative values by their absolute value like for i.. arr.get(i)! =abs(arr.get(i)) for j.. if arr.get(i)>arr.get(j) then swap so final array is -1, -2, 3,4,5 for example for given random numbers array and i mantain a max after each i and all j iterations per that I have if max<sum(i.e. sum+arr.get(allj)+arr(particular i) then max=sum. So this was giving me the max sum but I got 4 cases passed out of 14 and i thought the reason being sorted array wouldnt be always contiguous so any suggestions so as to how would i inculcate such contiguous logic within this to make it work for all cases.

答案1

得分: 1

我认为你把连续子数组问题错认为子集问题了,因为在逻辑中不应该使用排序。你可以参考这里的问题,它也处理了负数。https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

英文:

I think you mistook contiguous subarray problem to a subset problem instead cause you shouldn't be using sorting in the logic. You could refer the question here which handles negative numbers as well. https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

答案2

得分: 1

这个维基百科页面上对最大子数组问题有一个很好的解释。基本上,你在寻找Kadane算法的实现,该算法在文章中有解释。

英文:

There is an excellent explanation of the Maximum Subarray Problem on this page of Wikipedia. Essentially, you are looking for an implementation of Kadane's algorithm, which is explained in the article.

huangapple
  • 本文由 发表于 2020年10月7日 03:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64232378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定