Title: Returns the largest sub-array in an integer array
Requirements: Enter an array of shapes, there are integers in the array and there are negative numbers;
One or more consecutive integers in an array make up an integer group and each sub-array has one and;
The maximum value of all sub-arrays, requiring a time complexity of O (n).
Idea: Set the array to a[5], then all the sub-arrays and can be considered
(1) a[0]+a[1]+a[2]+a[3]+a[4] (2) a[1]+a[2]+[3]+a[4]
A[0]+A[1]+A[2]+A[3] a[1]+a[2]+[3]
A[0]+A[1]+A[2] a[1]+a[2]
A[0]+A[1] a[1]
A[0]
... and so on. And so on five groupings, each grouping has its maximum value, stored in the array max[5], and finally the maximum value of the array max[5] is the problem.
Specific implementation code:
1#include <iostream.h>2#include <conio.h>3 intMain ()4 {5 intarr[5];6 inti,j;7 intmax[5];8 intJixu;9cout<<"Input array:"<<Endl;Ten for(i=0;i<5; i++) One { ACin>>Arr[i]; - } - for(i=0;i<5; i++) the { -max[i]=Arr[i]; - } - for(j=0;j<4; j + +) + { - for(i=j+1;i<5; i++) + { Aarr[j]=arr[j]+Arr[i]; at if(max[j]<Arr[j]) - { -max[j]=Arr[j]; - } - } - } in for(i=0;i<5; i++) - { to if(max[0]<Max[i]) +max[0]=Max[i]; - } thecout<<"addmax="<<max[0]<<Endl; *cout<<"do you want to continue? Jixu (0, exit 1, continue)"<<Endl; $Cin>>Jixu;Panax Notoginseng if(jixu==1) - { thecout<<Endl; + main (); A } the Else + { - return 0; $ } $ getch (); - return 0; - the}
The idea of testing the code: integers include positive integers, 0, negative integers. Therefore, three integer cases need to be taken into account. In the specific test we used 4 sets of data to test, respectively:
(1) 0,0,0,0,0
(2) 1,1,1,1,1
(3) -1,-1,-1,-1,-1
(4) 1,0,2,-1,3
After testing, the program runs well, specifically as follows:
Knot Pair Experience:
Through this pair of activities, realize the importance of teamwork. After the teacher finished the homework, I and the small partners each have different ideas, mutual exchange of ideas and found their advantages and disadvantages, through the unity of opinion and programming and testing mutual help, and finally completed the teacher assigned tasks. The first time I completed the task quickly, I realized that it was important to develop.
A photo of me and my little friend:
Pair development of array pairs