There is an input array in the question. The numbers in the array are all integers, which may be positive, negative, or 0. The sum of the largest subarrays in the input array is required.
Question Analysis
In the face of such a problem, we need to carefully analyze the conditions and requirements of the problem. This problem provides an input array containing several elements. Each element can be a positive number, a negative number, or 0. The question requires that the sum of the largest sub-array in the array be output. Note that the sub-array composed of several elements adjacent to each other must be continuous and the sum of the sub-array must be the largest.
This problem is characterized by the specific optimal sub-structure, no post-efficiency, and other dynamic planning features. Therefore, it can be solved using dynamic planning.
Set the original input array to data [], and use another array DP [I] to represent the largest sum of subarrays ending with data [I:
DP [I] = max (sum (data [start... end]) 0 <= start <= end <= I
Therefore, the largest sub-array is the maximum value in the DP array.
In actual code implementation, You can simplify the DP array, replace it with a variable, and update the largest sum and the starting position and ending position of the sub-array in real time.
Code Section
The following code implements this question:
#define LENGTH 10int max_subset(int *data,int len,int *s,int *l){int max=0;int i,j;int sum=0;int start,end;for(i=0;i<len;i++){if(sum<=0){sum=data[i];start=end=i;}else{sum=sum+data[i];end=i;}if(sum>max){max=sum;*s=start;*l=end;}}if(max==0){max=data[0];*s=*l=0;for(i=1;i<len;i++){if(data[i]>max){max=data[i];*s=*l=i;}}}return max;}int main(){int data[LENGTH]={-1,-2,3,10,-4,7,-2,5,-9,-1};int result=0;int s,l;result=max_subset(data,LENGTH,&s,&l);printf(" max sub set is %d from %d to %d \n",result,s,l);return 0;}
Summary
This is a classic question and has been used by many companies in the test interview. It is worth studying carefully.