# 最大子序列和与最大矩阵

## 最大子矩阵

<题目来源：百度2017秋招，http://exercise.acmcoder.com/... >

### 问题描述

f[i] = max{f[i - 1] + a[i], a[i]} (1 <= i <= n, 其中f[i] = 0)

*更多的解题方法可以参考：
http://blog.csdn.net/hcbbt/ar...*

3 1 -5 7 3 5 -2

3 1 -5 7 3 5 -2
1 -2 3 5 -1 2 4
2 2 1 -3 2 5 3

3 1 -5 7 3 5 -2
or
1 -2 3 5 -1 2 4
or
2 2 1 -3 2 5 3
or
3 1 -5 7 3 5 -2
1 -2 3 5 -1 2 4
and so on...

4 -1 -2 12 2 7 2

val = sum[col, j] - sum[col, i - 1]

``````import sys

const_max_num = 100

def main():
matrix = [[0 for i in range(const_max_num + 1)]for i in range(const_max_num + 1)]
t_case = int(raw_input())

for t in range(t_case):
temp = raw_input().split(' ')
n = int(temp[0])
m = int(temp[1])

for i in range(1, n + 1):
line = raw_input().split(' ')
for j in range(1, m + 1):
matrix[i][j] = int(line[j - 1])

col_sum = [[0 for i in range(const_max_num + 1)]for i in range(const_max_num + 1)]
for col in range(1, m + 1):
for row in range(1, n + 1):
col_sum[col][row] = col_sum[col][row - 1] + matrix[row][col]

line = []
max_area = -sys.maxint
for row_start in range(1, n + 1):
for row_end in range(row_start, n + 1):
for i in range(1, m + 1):
line.append(col_sum[i][row_end] - col_sum[i][row_start - 1])
cur = 0
for l in line:
cur = max(cur + l, l)
max_area = max(max_area, cur)
line[:] = []

print max_area

if __name__ == '__main__':
main()``````

1 人关注
12 篇文章