Programming Algorithm-maximum and code of Continuous sub-array (c)

Source: Internet
Author: User
The largest continuous sub-array and code (c)


Address: http://blog.csdn.net/caroline_wendy


Question: enter an integer array with a positive or negative number in the array. One or more consecutive integers in the array form a subarray. Calculate the maximum value of the sum of all subarrays.


Save with a numberCurrent and, IfThe current sum is less than 0, Replace the new value. Otherwise, increment and save with a number.Temporary maximum value.


Code:

/** Main. CPP ** created on: June 29, 2014 * Author: Wang */# include <stdio. h> # include <limits. h> using namespace STD; int getgreatestsumofsubarray (int * pdata, int length) {If (pdata = NULL | length <= 0) return 0; int ncursum = 0, ngreatestsum =-int_max; For (INT I = 0; I <length; ++ I) {If (ncursum <= 0) ncursum = pdata [I]; else ncursum + = pdata [I]; If (ncursum> ngreatestsum) ngreatestsum = ncursum;} return ngreatestsum;} int main (void) {int data [] = {1, -2, 3, 10,-4, 7, 2,-5}; int result = getgreatestsumofsubarray (data, 8); printf ("result = % d \ n ", result); Return 0 ;}

Output:

result = 18










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.