To find the largest and most large array of sub-arrays

Source: Internet
Author: User
Tags array length

Enter an array of shaping. One or more consecutive integers in an array make up a sub-array, each of which has a and. The maximum value for the and of all sub-arrays.

    • Interface

Int getsubarraysum (int* pintarray,int ncount);

    • Specifications

Requires a time complexity of O (n)

    • Example

For example, the input array is 1,-2, 3, ten, -4, 7, 2, 5 , and the largest sub-array is 3, ten, -4, 7, 2 ,
so the output is the and of the sub-array -

This topic on Huawei OJ is slightly different from the sum of the largest subsequence in the introduction of algorithms, where it is not specified that if the array is all negative then we define the maximum subsequence and 0.
Therefore, we should judge this situation first, and then use the knowledge in dynamic programming to calculate the time complexity of N.

The complete code is as follows:

#include <stdlib.h> #include <string.h> #include "oj.h"/* Function:    input: Pintarray: Array, ncout: array length    output:     return: Returns the maximum value     */int getsubarraysum (int* pintarray, int ncount) {/    * here implements the function *    /if (pintarray==null| | ncount<1)    return-1;    int b=0,cnt=0,a=pintarray[0];  All negative cases for  (int i=0;i<ncount;i++)  {    if (pintarray[i]<0)  cnt++; if (A<pintarray[i])  a=pintarray[i];  }  if (Cnt==ncount)  return a; int thissum,maxsum,j; thissum = maxsum = 0; for (j = 0;j < ncount;j++) {    thissum + = pintarray[j];          if (Thissum > Maxsum)       maxsum = thissum;    else if (Thissum < 0)       thissum = 0;   }    return maxsum;}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

To find the largest and most large array of sub-arrays

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.