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.
Int getsubarraysum (int* pintarray,int ncount);
Requires a time complexity of O (n)
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