Maximum subarray problem brute force complexity

有些话、适合烂在心里 提交于 2019-12-12 06:50:48

问题


What is the runtime/memory complexity of the Maximum subarray problem using brute force?

Can they be optimized more? Especially the memory complexity?

Thanks,


回答1:


Brute force is Omega(n^2). Using Divide and conquer you can do it with Theta(n lg n) complexity. Further details are available in many books such as Introduction to Algorithms, or in various resources on the Web, such as this lecture.




回答2:


As suggested in this answer you can use Kadane's algorithm which has O(n) complexity. An implementation in Java:

public int[] kadanesAlgorithm (int[] array) {
        int start_old = 0;
        int start = 0;
        int end = 0;
        int found_max = 0;

        int max = array[0];

        for(int i = 0; i<array.length; i++) {
            max = Math.max(array[i], max + array[i]);
            found_max = Math.max(found_max, max);
            if(max < 0)
                start = i+1;
            else if(max == found_max) {
                start_old=start;
                end = i;
                }
        }

        return Arrays.copyOfRange(array, start_old, end+1);
    }


来源:https://stackoverflow.com/questions/5649754/maximum-subarray-problem-brute-force-complexity

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