I. Question requirements
Question: return the sum of the largest subarrays in a two-dimensional integer array. Requirement: enter a two-dimensional integer array with a positive or negative number in the array. The two-dimensional array is connected at the beginning and end, just like a first-and-tail-connected string. One or more consecutive integers in the array form a sub-array. Each sub-array has a sum. Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ). Code:
# Include <iostream>
Using namespace STD;
Int maxsubarray (INT ** A, int N, int m)
{
Int ** P = new int * [N];
Int I, J;
If (M = 0 | n = 0)
Return 0;
// Calculate P [I] [J]
For (I = 0; I <n; I ++)
{
P [I] = new int [m];
For (j = 0; j <m; j ++)
{
If (I = 0)
{
If (j = 0)
P [I] [J] = A [I] [J];
Else
P [I] [J] = P [I] [J-1] + A [I] [J];
}
Else
{
If (j = 0)
P [I] [J] = P [I-1] [J] + A [I] [J];
Else
P [I] [J] = P [I] [J-1] + P [I-1] [J]-P [I-1] [J-1] + A [I] [J];
}
}
}
// Calculate the sum of the largest child arrays of two-dimensional arrays
Int temp;
Int max = A [0] [0];
Int ans;
// If M = 1
If (M = 1)
{
For (I = 0; I <n; I ++)
{
For (j = I; j <n; j ++)
{
If (I = 0)
{
Temp = P [J] m-1];
}
Else
{
Temp = P [J] [M-1]-P [I-1] [m-1];
}
If (ANS <temp)
Ans = temp;
}
}
}
Else
{
For (I = 0; I <n; I ++)
{
For (j = I; j <n; j ++)
{
If (I = 0)
{
Temp = P [J] [M-1]-P [J] [m-2];
}
Else
{
Temp = P [J] [m-1]-P [J] [m-2]-P [I-1] [m-1] + P [I-1] [m-2];
}
For (int K = m-2; k> = 0; k --)
{
If (temp <0)
Temp = 0;
If (I = 0)
{
If (k = 0)
Temp + = P [J] [k];
Else
Temp + = P [J] [k]-P [J] [k-1];
}
Else
{
If (k = 0)
Temp + = P [J] [k]-P [I-1] [k];
Else
Temp + = P [J] [k]-P [J] [k-1]-P [I-1] [k] + P [I-1] [k-1];
}
If (ANS <temp)
Ans = temp;
}
}
}
}
Return ans;
}
Int main ()
{
Int n, m, temp;
Int a1, a2;
Int K = 0;
Printf ("Enter the number of rows and columns of a two-dimensional array: \ n ");
Scanf ("% d", & N, & M );
Int I, J;
Int ** A = new int * [N];
Printf ("Enter % d * % d Two-dimensional array elements: \ n", n, m );
For (I = 0; I <n; I ++)
{
A [I] = new int [m];
For (j = 0; j <m; j ++)
{
Scanf ("% d", & A [I] [J]);
}
}
Int ans = maxsubarray (A, n, m );
Printf ("the sum of the largest subarrays of two-dimensional arrays is: % d \ n", ANS );
For (A2 = 0; a2 <m-1; a2 ++)
{For (I = 0; I <n; I ++)
{Temp = A [I] [0];
For (j = 1; j <m; j ++)
{A [I] [J-1] = A [I] [J];}
A [I] [M-1] = temp;
}
For (I = 0; I <n; I ++)
{
For (j = 0; j <m; j ++)
{
If (K % m = 0)
{Cout <Endl ;}
Cout <A [I] [J] <"";
K ++;
}
}
A1 = maxsubarray (A, n, m );
Printf ("the sum of the largest subarrays of two-dimensional arrays is: % d \ n", A1 );
}
Return 0;
}
Running result:
Paired person photo:
Pair Exercise 2