max_rect2.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. '''
  2. > https://www.codingame.com/ide/1850615487c96262f26bd2d508cb46b18cc23557
  3. @author: olivier.massot, 2019
  4. '''
  5. import sys
  6. from copy import deepcopy
  7. # w, h = [int(i) for i in input().split()]
  8. # rows = [[int(x) for x in input().split()] for _ in range(h)]
  9. w,h=2,2
  10. rows = [[-1,99],
  11. [0,2]
  12. ]
  13. def findMaxSubmatrix(matrix, height, width):
  14. nrows = len(matrix)
  15. ncols = len(matrix[0])
  16. cumulative_sum = deepcopy(matrix)
  17. for r in range(nrows):
  18. for c in range(ncols):
  19. if r == 0 and c == 0:
  20. cumulative_sum[r][c] = matrix[r][c]
  21. elif r == 0:
  22. cumulative_sum[r][c] = cumulative_sum[r][c-1] + matrix[r][c]
  23. elif c == 0:
  24. cumulative_sum[r][c] = cumulative_sum[r-1][c] + matrix[r][c]
  25. else:
  26. cumulative_sum[r][c] = cumulative_sum[r-1][c] + cumulative_sum[r][c-1] - cumulative_sum[r-1][c-1] + matrix[r][c]
  27. best = 0
  28. for r1 in range(nrows):
  29. for c1 in range(ncols):
  30. r2 = r1 + height - 1
  31. c2 = c1 + width - 1
  32. if r2 >= nrows or c2 >= ncols:
  33. continue
  34. if r1 == 0 and c1 == 0:
  35. sub_sum = cumulative_sum[r2][c2]
  36. elif r1 == 0:
  37. sub_sum = cumulative_sum[r2][c2] - cumulative_sum[r2][c1-1]
  38. elif c1 == 0:
  39. sub_sum = cumulative_sum[r2][c2] - cumulative_sum[r1-1][c2]
  40. else:
  41. sub_sum = cumulative_sum[r2][c2] - cumulative_sum[r1-1][c2] - cumulative_sum[r2][c1-1] + cumulative_sum[r1-1][c1-1]
  42. if best < sub_sum:
  43. best = sub_sum
  44. return best
  45. print(findMaxSubmatrix(rows,h,w))