本文共 2682 字,大约阅读时间需要 8 分钟。
kadane算法
What is a sub-array?
什么是子阵列?
A sub-array is basically an array's contiguous part. For example, if we have an array of integers [1,2,3] so the sub-arrays that we can form from the given array are [1], [2] , [3] , [1,2] , [2,3] , [1,2,3].
子数组基本上是数组的连续部分。 例如,如果我们有一个整数数组[1,2,3],那么我们可以从给定数组形成的子数组为[1],[2],[3],[1,2],[ 2,3],[1,2,3] 。
So in the above example the sum of all the respective sub-arrays are 1,2,3,3,5,6. So here in this problem, we are required to find the maximum sub-array sum that could be obtained from a sequence of integers, which is 6 in the above case.
因此,在上面的示例中,所有各个子数组的总和为1,2,3,3,5,6 。 因此,在此问题中,我们需要找到可以从整数序列获得的最大子数组和,在上述情况下为6 。
So many algorithms could be opted to solve the above problem, for example, a simple brute-force algorithm can be → that we can simply compute the sum of all the sub-arrays then loop through all those sums to compute maximum of those, but this algorithm will take O(N*N*N) time or in the best case O(N*N) if we try to do some pre-computation by making a cumulative some array also called a prefix sum array.
可以选择很多算法来解决上述问题,例如,可以使用简单的蛮力算法→这样我们就可以简单地计算所有子数组的总和,然后循环遍历所有这些总和以计算出这些总和的最大值。如果我们尝试通过使累积的某个数组也称为前缀和数组来进行一些预计算,则此算法将花费O(N * N * N)时间,或者在最佳情况下为O(N * N) 。
So now why should we prefer KADANES's ALGORITHM?
那么,现在为什么我们应该选择KADANES的算法 ?
It is because this algorithm can solve our problem in O(N) time that is we can obtain the maximum sub-array sum in linear time complexity which is the most optimal solution for our task.
因为该算法可以解决O(N)时间的问题,所以我们可以获得线性时间复杂度的最大子数组和,这是我们任务的最佳解决方案。
So let us now quickly try to understand the Kadane's Algorithm in two simple steps.
因此,让我们现在通过两个简单的步骤快速尝试理解Kadane算法 。
Initialize two variables named CS (current sum) and MS (max sum) with 0
用0初始化两个名为CS(当前和)和MS(最大和)的变量。
Loop for each element of the array and do these below tasks for each iteration,
循环访问数组的每个元素,并为每次迭代执行以下任务,
Description: So basically if we have to find the maximum sub-array sum of a given array then the most optimal solution is KADANE'S ALGORITHM, which can easily perform the desired task in linear time complexity that is it will take O(N) time.
描述:因此基本上,如果我们必须找到给定阵列的最大子阵列总和,则最佳解决方案是KADANE算法 ,该算法可以轻松地以线性时间复杂度执行所需任务,这将花费O(N)时间。
SO now let us quickly jump to the coding part!
现在让我们快速跳转到编码部分!
Code:
码:
#includeusing namespace std;int main(){ cout<<"Enter the size of an array: "; int n; cin>>n; int ar[100],cs,ms; ms=0;cs=0; cout<<"Enter the array elements:"< >ar[i]; for(int i=0;i
Output
输出量
Enter the size of an array: 6Enter the array elements:1 2 3 -4 6 -1The maximum subarray sum is:8
翻译自:
kadane算法
转载地址:http://rwxzd.baihongyu.com/