Home > Web Front-end > JS Tutorial > body text

Interesting JavaScript question: Find the maximum sum of subarrays

黄舟
Release: 2017-01-22 14:47:58
Original
1714 people have browsed it

This is an integer array [1,-1,2], which has the following subarrays:

1.[1] sum=>1

##2.[1 ,-1] sum=>0

3.[1,-1,2] sum=>2

4.[-1] sum=>-1

5.[-1,2] sum=>1

6.[2] sum=>2

As you can see, in these sub-arrays, each The maximum sum of elements is 2.

So given any integer array, how to find the sum of its largest subarrays?

If you look carefully at the order in which I listed the subarrays above, you can see that this is exhaustive starting from the first one.

Well, my method is exhaustive, and the execution process is exactly as shown above.

The efficiency of the exhaustive method in realizing this problem is actually not low, and it can meet general needs.

I start from the first element and need to traverse N elements.

Starting from the second element, N-1 elements need to be traversed.

......

The last element starts with only itself, 1 element.

In other words, the actual complexity of the exhaustive method is N²/2, which is quite efficient.

function maxContiguousSum (arr) {  
    var max = 0;  
    for(var i=0;i<arr.length;i++){  
        var temp = 0;  
        for(var j=i;j<arr.length;j++){  
            temp += arr[j];  
            if(temp > max){  
                max = temp;  
            }  
        }  
    }  
    return max;  
}
Copy after login

The above is an interesting JavaScript question: finding the sum of the largest subarray. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!