给定一个 nxn 的矩阵,找到一个 mxm 的子矩阵,其中 m=1,使得矩阵 mxm 的所有元素之和最大。矩阵 nxn 的输入可以包含零、正整数和负整数值。

示例
Input:
{{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5} }
Output:
4 4
5 5
上面的问题可以通过一个简单的解决方案来解决,我们可以取整个矩阵 NxN,然后找出所有可能的 MxM 矩阵并求出它们的和,然后打印具有最大和的 MxM 矩阵。这种方法很简单,但需要 O(N^2.M^2) 时间复杂度,因此我们尝试找到一种时间复杂度较小的方法。
算法
Start
Step 1 -> Declare Function void matrix(int arr[][size], int k)
IF k>size
Return
Declare int array[size][size]
Loop For int j=0 and j<size and j set sum="0" for int i="0" arr array arrayi maxsum="INT_MIN" null loop end if> maxsum
Set maxsum = sum
Set pos = &(arr[i][0])
End
Loop For int j=1 and j<size-k and j sum array> maxsum
Set maxsum = sum
Set pos = &(arr[i][j])
End
End
End
Loop For int i=0 and i<k and i loop for int j="0" end print>
End
Step 2 -> In main()
Declare int array[size][size] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}}
Declare int k = 2
Call matrix(array, k)
Stop</k></size-k></size>
示例
#include <bits>
using namespace std;
#define size 5
void matrix(int arr[][size], int k){
if (k > size) return;
int array[size][size];
for (int j=0; j<size j int sum="0;" for i="0;" arr maxsum="INT_MIN," null array if> maxsum){
maxsum = sum;
pos = &(arr[i][0]);
}
for (int j=1; j<size-k j array> maxsum){
maxsum = sum;
pos = &(arr[i][j]);
}
}
}
for (int i=0; i<k i for j="0;" cout endl int main array k="2;"><h2>输出</h2>
<p>如果我们运行上面的程序,那么它将生成以下输出</p>
<pre class="brush:php;toolbar:false;">4 4
5 5











