Requirements:Enter a two-dimensional shaping array with positive numbers in the array and a negative number. A two-dimensional array is connected to the end of the line, like a belt. 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.
Ideas:Based on the previous several ideas about one-dimensional and two-dimensional arrays, integrate them. The two-dimensional array is converted into one-dimensional array, and then the maximum Subarray and (loop) of one-dimensional array are solved.
1#include <iostream>2#include <cstdio>3#include <ctime>4 using namespacestd;5 #defineM 46 #defineN 47#include <memory.h>8 9 intMaxsubarray (int*arr,intSize//maximum sub-sequences andTen { One inti, Sum, MAX1, MAX2, DP, min; ADP = MAX1 = arr[0]; - for(i =1; i < size; ++i)//non-annular array; ++i, I add 1 first, then I use the value - { the if(DP <0) -DP =Arr[i]; - Else -DP + =Arr[i]; + if(DP >max1) -Max1 =DP; + } Asum = min = DP = arr[0]; at for(i =1; i < size; ++i)//The smallest subarray of arrays and, again, all elements of the array and subtract, the result crosses arr[n-1] to arr[0] - { - if(dp>0) -DP =Arr[i]; - Else -DP + =Arr[i]; in if(DP <min) -Min =DP; toSum + =Arr[i]; + } -Max2 = Sum-min;//array all elements and minus minimum sub-arrays the returnMax1>max2? MAX1:MAX2;//three mesh operator; if max1>max2, returns the value of MAX1, otherwise returns MAX2 * } $ intMaxsubmatrix (intNintMintArray[m][n])Panax Notoginseng { - intI, J, H, max, sum =-100000; the intb[ -]; + for(i =0; i<n; i++) A { thememset (b,0,sizeof(b));//Initialize b[] + for(j = i; j<n; j + +)//Add the line I to line J to find the maximum value for each addition - { $ for(h =0; h<m; h++) $ { -B[H] + = array[j][h];//Two-dimensional arrays are compressed into one-dimensional arrays, and then the maximum subsequence and - } theMax =Maxsubarray (b, h); - Wuyi if(max>sum) thesum =Max; - } Wu } - returnsum; About } $ intMain () - { - intArr[m][n]; -cout <<"a random two-dimensional array is:"<<Endl; ASrand (Time (0)); + for(inti =0; i < M; i++) the { - for(intj =0; J < N; J + +) $ { theARR[I][J] = rand ()% -- -; thecout << Arr[i][j] <<" "; the } thecout <<Endl; - } incout <<"the and of the largest sub-arrays:"<< Maxsubmatrix (M, N, arr) <<Endl; the return 0; the}
Summary: each program after the end should be their own programs to save, easy to reuse, at the same time, it can be seen that the program to achieve the benefits of the module.
Returns the sum of the largest sub-arrays in a two-dimensional array of integers (loops)