最小和子阵列O(N)由Kadane算法阵列、算法、最小、Kadane

2023-09-11 02:09:05 作者:假装狠心的自己

我们都知道的最大总和子数组和著名 Kadane算法。但是,我们使用相同的算法找出最小之和也?

我的看法是:

  

改变的迹象,找到最大一笔在于,同我们计算的最高数额子数组的方式。不是改变的标志   数组中的元素,使其在初始状态。

请帮我纠正算法中,如果有任何问题。

角落情况:我知道有一个问题,如果所有的元素都是积极的,我们可以做一些preprocessing即遍历数组处理这种情况下,如果所有的+已经不仅仅是回报从阵列的最小数目。

上面提到的算法将工作和良好的支持(解释)由dasblinkenlight.

解决方案   

将我所提到的工作方法来找到最小总和?

是的,会的。可以重新陈述找到最小和作为查找负总和与最大绝对值的问题。当您打开数字的迹象,并保持了算法的地方休息,这就是数字,该算法将要返回给你。

  

我知道有一个问题,如果所有的元素都是正

AcWing算法基础课 最长上升子序列 II

没有,有没有问题:考虑原来Kadane的算法,当所有的元素都是负面的。在这种情况下,该算法返回的零总和空序列 - 的一种可能的情况下最高。换句话说,当所有的元素是负的,你的最好的解决办法是把它们都不

您改进算法会做同样的情况下,当所有的数字是积极的。再次,你最好的办法是在所有不带数字

如果您添加的范围内返回从算法回可能不是空的一个要求,你可以修改算法略有找到的最小正数(或最大的负数)的情况下Kadane的算法返回一个空的范围内最优解。

We all know about the maximum sum subarray and the famous Kadane's algorithm. But can we use the same algorithm to find minimum sum also?

My take is:

change the sign and find the max sum in that, same as the way we calculate the maximum sum subarray. Than change the sign of the elements in the array to make it in initial state.

Please help me in correcting the algo if it has any issue.

corner case: I know there is an issue if all the elements are positive and we can handle this case by doing some preprocessing i.e. traverse the array if all are +ve than just return the minimum number from the array.

The above mention algorithm will work and well supported (explained) by dasblinkenlight.

解决方案

Will the approach that I have mentioned work to find the minimum sum?

Yes, it will. You can re-state the problem of finding the minimum sum as finding a negative sum with the largest absolute value. When you switch the signs of your numbers and keep the rest of the algorithm in place, that's the number that the algorithm is going to return back to you.

I know there is an issue if all the elements are positive

No, there's no issue: consider the original Kadane's algorithm when all elements are negative. In this case the algorithm returns an empty sequence for the sum of zero - the highest one possible under the circumstances. In other words, when all elements are negative, your best solution is to take none of them.

Your modified algorithm is going to do the same in case when all numbers are positive: again, your best solution is to not take numbers at all.

If you add a requirement that the range returned back from the algorithm may not be empty, you could modify the algorithm slightly to find the smallest positive number (or the greatest negative number) in case when Kadane's algorithm returns an empty range as the optimal solution.