A title: A two-dimensional array, with a positive number, a negative number, to find its maximum sub-matrix.
Two design ideas:
This problem is basically no difficulty, because this problem can refer to the previous one to solve the two-dimensional array of sub-matrices (not the end-to-end), so it can be divided into two simple parts. The first step is to turn it into a one-dimensional array (loop), and then solve the idea of maximal sub-arrays in the solution loop. Refer to the two-dimensional array as a one-dimensional array (http://www.cnblogs.com/houtaoliang/p/4401630.html), where only the largest sub-array of the solution ring is simply analyzed.
The maximum number of sub-arrays for the solution ring can be divided into two cases. First: When the array subscript is not out of bounds, for example, -2 1 5 9 -6 4, the maximum subarray is 1 5 9. The idea of dynamic programming can be used to solve this problem. Assume that the maximum subarray is a[i]--a[j-1], which makes sum=a[i]+. +A[J-1], if it is the largest sub-array must have SUN+A[J]>A[J] that is sum>0, otherwise a[j] assigned to sum. The second case is when the array is out of bounds, such as 1 3 2 -9-4 6
this is equivalent to solving the smallest subarray in the array (as with the maximum subarray principle), and then using the entire array and subtracting the youngest array, the maximum subarray is obtained.
Three codes
#include <iostream>using namespacestd;intMAX (intS[],intN) { inti,sum=0, max=s[0]; for(i=0; i<n;i++) { if(sum>0) {sum=sum+S[i]; } Else{sum=S[i]; } if(sum>max) {Max=sum; } } returnMax;}intMIN (intS[],intN) { inti,sum=0, min=s[0]; for(i=1; i<n;i++) { if(sum<0) {sum=sum+S[i]; } Else{sum=S[i]; } if(sum<min) {min=sum; } } returnmin;}intSUM (intS[],intN) { inti,sum=0; for(i=0; i<n;i++) {sum=sum+S[i]; } returnsum;}voidMain () {intm,n,i,j,a[ -][ -]; cout<<"Please enter the size of the Matrix (m*n):"; CIN>>m>>N; cout<<"Please enter a matrix:"<<Endl; for(i=0; i<m;i++) { for(j=0; j<n;j++) {cin>>A[i][j]; } } intsum,max,s[ -],k=0, min,p=a[0][0]; for(i=0; i<m;i++) { for(j=0; j<n;j++) {S[j]=0; } while(k+i<m) { for(j=0; j<n;j++) {S[j]=s[j]+a[k+i] [j]; } Sum=SUM (s,n); Min=MIN (s,n); Max=MAX (s,n); if(sum-min>max) {Max=sum-min; } if(max>p) {p=Max; } k++; } k=0; } cout<<"the maximum value of the sub-matrix is"<<p<<Endl;}
Four
End-to-end two-dimensional array (cylinder)--the maximal sub-matrix