Fhernd icon

matrix-land.py

Fhernd | PRO | 11/11/18 07:15:00 PM UTC | 0 ⭐ | 1199 👁️ | Never ⏰ | []
Python |

1.19 KB

|

None

|

0 👍

/

0 👎

import sys
from array import array
 
def matrixLand(grid):
    width = len(grid[0])
    prevline = array('l',[0]) * width
    
    for line in grid:
        going_left = array('l',[0]) * width
        going_right = array('l',[0]) * width
        
        top, notop = -2000000000, 0
        for i in range(width):
            notop = max(0,notop)
            going_right[i] += notop
            notop += line[i]
            top = max(top+line[i], prevline[i]+notop)
            going_left[i] += top
 
        top, notop = -2000000000, 0
        for i in range(width-1,-1,-1):
            notop = max(0,notop)
            going_left[i] += notop
            notop += line[i]
            top = max(top+line[i], prevline[i]+notop)
            going_right[i] += top
            
        for i in range(width):
            prevline[i] = max(going_left[i], going_right[i])
            
    return max(prevline)
 
 
n, m = [int(x) for x in input().split()]
 
if m == 1:
    print(sum(int(x) for x in sys.stdin))
else:    
    grid = []
    for _ in range(n):
        grid.append(array('l',(int(x) for x in sys.stdin.readline().split(' '))))
    result = matrixLand(grid)
    print(result)

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎