The topic is connected as follows:
Http://www.acmerblog.com/max-sum-rectangle-in-a-matrix-5955.html
The largest and most contiguous subarray of a one-dimensional array
Title: Enter an array of integers with positive and negative numbers in the array. One or more consecutive integers in an array make up a sub-array. The maximum value for the and of all sub-arrays. The required time is O (n).
If the input array is {1,-2,3,10,-4,7,2,-5}, we try to accumulate the positive numbers from beginning to end, initialize and 0, the first step plus 1, at this time and 1, the second step plus-2, and then 1, the third step plus 3, at which point we find -1+3= 2, the maximum and 2 are smaller than the 31 individual integers, which is because 3 adds a negative number, and after discovering this rule we re-add the condition: if current and negative, discard the preceding sum, and start counting from the next count in the array.
Sword refers to offer and programming beauty have this problem. Reference here: The Sword refers to offer (14)-the maximum sub-vector and nine degrees 1372. The algorithm can be optimized for the following lines of code:
The largest and most contiguous subarray of a two-dimensional array
A contiguous subarray of two-dimensional arrays is a matrix, as shown in
The top vertex of the matrix is a (I,J) and the lower right vertex is B (Endi, ENDJ). In the figure is a (a), B (3,3). We can use Rect (A, B) (1,1,3,3,) to represent rectangular regions.
Code:
#include <cstdio>#include<iostream>using namespacestd;inta[ -][ -];intn,m;intp[ -][ -];intMain () {Freopen ("In.txt","R", stdin); inti,j; intMax, IMAX, Jmax, Istart, Jend; while(~SCANF ("%d%d",&n,&m) {memset (A,0,sizeof(a)); for(i =0; I < n; i++ ) { for(j =0; J < M; J + +) {scanf ("%d",&A[i][j]); P[I][J]=A[i][j]; if(J-1>=0) P[i][j]+ = p[i][j-1]; ifI1>=0) P[i][j]+ = p[i-1][j]; if(I-1>=0&& J1>=0) P[i][j]-= p[i-1][j-1]; } } for(i =0; I < n; i++ ) { for(j =0; J < M; J + +) printf ("%3d", P[i][j]); printf ("\ n"); } Max= a[0][0]; inttemp, Tempstart, tempend; intZ; for(i =0; I < n; i++ ) { for(j = i; J < N; j + +) {Temp= p[j][0]; ifI1>=0) Temp-= p[i-1][0]; Tempstart= Tempend =0; for(z =1; Z < m; z++) { intZZ =P[j][z]; if(Z-1>=0) ZZ-= p[j][z-1]; ifI1>=0) ZZ-= p[i-1][z]; if(I-1>=0&& Z1>=0) ZZ+ = p[i-1][z-1]; if(temp + ZZ) >ZZ) {Temp= temp +ZZ; Tempend=Z; } Else{Temp=ZZ; Tempstart= Tempend =Z; } if(Temp >max) {Max=temp; Imax= i; Jmax =J; Istart= Tempstart; Jend =Tempend; } }}} printf ("(%d,%d)-(%d,%d) sum is%d \ n", IMAX, Istart, Jmax, Jend, Max); } return 0;}
The maximum and large of successive sub-arrays (two-dimensional)