Title Requirements:
Returns the maximum number of sub-arrays in a one-dimensional array
Enter an array of shapes with positive and negative numbers in the array.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
If the array a[0] ... A[j-1] next to each other, allowing a[i-1], ... A[n-1], a[0] ... A[J-1] and the largest.
Returns the position of the largest subarray at the same time.
The maximum value for the and of all sub-arrays.
Requires a time complexity of O (n)
Design ideas: (pair thinking and reference to other students)
Consider that the array needs to be connected to the end, take the length of the array to increase twice times, and the copied array is written in the back of the last number, so that in the process of the loop does not need to adopt a new algorithm, as long as the original code slightly modified, plus a decision to make the largest array of the length of the original array.
Program Source code:
#include <iostream.h> #include <stdlib.h>int main () {int num,length,start,finish; start=0; finish=0; cout<< "Please enter the number of array elements:"; cin>>length; num=2*length;//allocation twice times array space, convenient next time compare int* array=new int[num]; Allocates an array space for (int i=0;i<length;i++)//array plus and minus alternating occurrences {if (i%2==0) Array[i]=rand ()%1000;elsearray[i]=0-(rand ()%1000); }cout<< "Array is:"; for (i=0;i<length;i++) {cout<<array[i]<< ""; } cout<<endl;//The following code reference with other classmates as well as degrees Niang int max=array[0]; int sum=0; Defines the sum variable for (i=0;i<length;i++) {sum=0; for (int j=i;j<length+i;j++) {sum=sum+array[j]; if (Sum>max) {max=sum; start=i; Finish=j; }} Array[length+i]=array[i]; Each time the calculated number is put to the last} if (finish>=length) {cout<< "maximum subarray start position:" <<start+1<<endl; cout<< "Maximum sub-array end position:" <<finish-length+1<<endl; } else {cout<< "Maximum sub-array start position:" <<start+1<<endl; cout<< "Maximum sub-array end position:" <<finish+1<<endl; } cout<< "Maximum sub-array:" <<endl; for (int m=start;m<=finish;m++) {cout<<array[m]<< ""; } cout<<endl; cout<< "The number of the largest sub-arrays is:" <<endl; cout<<max<<endl; delete []array; return 0;}
Operation Result:
This pair of photos:
Too much food, or a low-key point.
Experiment Summary:
I can't solve the problem, so I send it late. Finally refer to other great God classmate's code, and fully understand the essence of the problem solving. In the future to improve their ability, too much food.
Pair development _ Maximum value of the loop array