Instance code for the largest sum of sub-Arrays

Source: Internet
Author: User

Question:
Enter an integer array, and the array contains positive and negative numbers.
One or more consecutive integers in the array form a sub-array. Each sub-array has a sum.
Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ).

For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the maximum sub-array is 3, 10,-4, 7, 2,
Therefore, the output is the sum of 18 of the sub-array.

Find the state transition equation. dp [I] indicates the largest sum of subarrays containing I in the first I count. Either the number I is the largest, or he wants to be joined together with the largest child array containing the I-1 (that is, dp [I-1.
That is, dp [I] = max {arr [I], dp [I-1] + arr [I]};

The Code is as follows;

Copy codeThe Code is as follows: # include <stdio. h>
# Define max (a, B) (a)> (B )? (A) :( B)

Int res (int * arr, int len ){
// Learn a method to define the minimum number :)
Int max =-(1 <31 );
Int I;
For (I = 1; I <len; I ++ ){
Arr [I] = max (arr [I], arr [I-1] + arr [I]);
If (max <arr [I]) max = arr [I];
}
Return max;
}

Int main (){
Int arr [] = {1,-2, 3, 10,-4, 7, 2,-5 };
Printf ("% d \ n", res (arr, 8 ));
Return 0;
}

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.