Returns the maximum value of a continuous sub-array in an array.

Source: Internet
Author: User
Problem:

Returns the maximum number of consecutive subarrays and values in an array. Example: {31,-187, 26,-, 97,-93,-}, the maximum value is 59 + 26-53 + 58 + 97 =

Ideas:

When calculating the sum of consecutive subarrays between I and j, the maximum value is certainly obtained, but the time complexity is O (n ^ 2). We hope to find a linear time algorithm.

We noticed that,If all values in the array are positive, the largest and all values must be added together. If there is a negative number in the array and a negative number is added, the sum of the values of the subarray is less than 0, then the maximum and sub-arrays must not contain this negative number.Based on this, the following code is provided:

// Calculate the maximum and # include <stdio. h> int getmaxvalue (INT data [], int length) {int max = 0, temp = 0; int I = 0; for (I = 0; I <length; I ++) {temp = temp + data [I]; If (temp <0) temp = 0; else {If (temp> MAX) max = temp ;}} return Max;} int main () {int data [] = {31,-, 26,-, 97,-93 }; int length = sizeof (data)/sizeof (INT); int max = getmaxvalue (data, length); printf ("% d", max );}

The time complexity is O (n)

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.