JavaScript fun: The sum of the largest subarrays

Source: Internet
Author: User
JavaScript fun: This is an integer array [1,-1, 2]. It has the following sub-arrays:

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

We can see that the sum of the elements in these subarrays is 2 at the maximum.

How can we calculate the sum of the largest sub-array of an integer array?

If you carefully observe the sequence of the sub-arrays listed above, we can see that this is from the first place to the beginning.

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

In fact, the efficiency of the problem is not low, and can meet general requirements.

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

The second element starts and needs to traverse the N-1 elements.

......

The last element has only one element at the beginning.

That is to say, 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 max) {max = temp ;}} return max ;}

The above is the JavaScript interesting question: the content for solving the sum of the largest subarrays. For more information, see PHP Chinese Network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.