Linear time algorithm for Maximum contiguous sub-array sum

我的梦境 提交于 2020-01-30 11:42:25

问题


I have been solving exercise from Introduction to Algorithms - CLRS and came across solving maximum contiguous sub-array in linear time (Q 4.1-5). Please look at my solution below. I have been searching for online judges for this exercise but found none. After solving it when I looked for solutions I found kadane's algorithm which seems different than my implementation also this solution gives the correct output when all numbers are negative.

public static int linearMaxSolve(int[] arr) {
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i : arr) {
    sum += i;
    if (i > sum) {
        sum = i;
    }
    if (sum > max) {
        max = sum;
    }
}
return max;
}

Is there a way to check the validity of this algorithm apart from feeding in manual test cases to the program?


回答1:


This really depends on what is your definition for an array with all negative values.

In case you don't count the empty sub-array as a possible solution then yes, your solution is correct and actually it's exactly the same as the Kadane's algorithm.

int max_so_far = a[0];
int max_ending_here = a[0];

for (int i = 1; i < size; i++)
{
    max_ending_here = Math.max(a[i], max_ending_here+a[i]);
    max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;

The only difference is the initialization, but if you'll take a closer look, at the first iteration of your algorithm, both sum and max will have the value of a[0].

But again, you assume here that both your array isn't empty (in that case you'll return Integer.MIN_VALUE, is that what you want?) and that an empty sub-array (sum==0) is not a possible solution.



来源:https://stackoverflow.com/questions/49217437/linear-time-algorithm-for-maximum-contiguous-sub-array-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!