Maximum Sum
Background
A problem that is simple to solve in one dimension is often much more difficult to solve in more than one dimension. consider satisfying a boolean expression in conjunctive normal form in which each conjunct consists of exactly 3 disjuncts. this problem (3-SAT) is NP-complete. the problem 2-SAT is solved quite efficiently, however. in contrast, some problems belong to the same complexity class regardless of the dimensionality of the problem.
The Problem
Given a 2-dimenstmarray of positive and negative integers, find the sub-rectangle with the largest sum. the sum of a rectangle is the sum of all the elements in that rectangle. in this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. A sub-rectangle is any contiguous sub-array of size or greater located within the whole array. as an example, the maximal sub-rectangle of the array:
Is in the lower-left-hand corner:
And has the sum of 15.
Input and Output
The input consists of an array of integers. the input begins with a single positive integer N on a line by itself indicating the size of the square two dimen=array. this is followed by integers separated by white-space (newlines and spaces ). these integers make up the array in row-major order (I. e ., all numbers on the first row, left-to-right, then all numbers on the second row, left-to-right, etc .). N may be as large as 100. the numbers in the array will be in the range [-127,127].
The output is the sum of the maximal sub-rectangle.
Sample Input
4
0-2-7 0 9 2-6 2
-4 1-4 1-1
8 0-2
Sample Output
15. A matrix is given. The sum of one and the largest child matrices is required ..
Idea: it is a bit similar to finding the largest and sub-sequences in one dimension. But this is two-dimensional. Direct violence times out. Therefore, each operation is performed. Keep the value. For later use. This greatly reduces the time used ..
Code:
# Include <stdio. h> # include <string. h> # include <limits. h> int n, num [105] [105], Max, he, sum [105]; void init () {Max =-INT_MAX; for (int I = 0; I <n; I ++) for (int j = 0; j <n; j ++) scanf ("% d ", & num [I] [j]) ;}int solve () {for (int I = 0; I <n; I ++) {memset (sum, 0, sizeof (sum); for (int j = I; j <n; j ++) {he = 0; for (int k = 0; k <n; k ++) {sum [k] + = num [j] [k]; if (he> = 0) // this step is followed by finding the maximum subsequence and a principle .. If it is a negative value, the sum will be reduced. Therefore, it starts from the next position. He + = sum [k]; else he = sum [k]; if (Max