classSolution { public: intmaxScore(vector<vector<int>>& grid){ int ans = grid[0][1] - grid[0][0]; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { int original = grid[i][j]; if (i > 0) { grid[i][j] = min(grid[i][j], grid[i - 1][j]); ans = max(ans, original - grid[i - 1][j]); } if (j > 0) { grid[i][j] = min(grid[i][j], grid[i][j - 1]); ans = max(ans, original - grid[i][j - 1]); } } } return ans; } };
执行用时分布119ms击败99.11%;消耗内存分布55.80MB击败87.46%。
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from typing importList
classSolution: defmaxScore(self, grid: List[List[int]]) -> int: ans = grid[0][1] - grid[0][0] for i inrange(len(grid)): for j inrange(len(grid[0])): original = grid[i][j] if i > 0: grid[i][j] = min(grid[i][j], grid[i - 1][j]) ans = max(ans, original - grid[i - 1][j]) if j > 0: grid[i][j] = min(grid[i][j], grid[i][j - 1]) ans = max(ans, original - grid[i][j - 1]) return ans
funcmin(a int, b int)int { if a < b { return a } return b }
funcmax(a int, b int)int { if a > b { return a } return b }
funcmaxScore(grid [][]int)int { ans := -12345678 for i, line := range grid { for j, item := range line { original := item if i > 0 { grid[i][j] = min(grid[i][j], grid[i - 1][j]) // 这里修改item的值不会改变grid[i][j]的值 ans = max(ans, original - grid[i - 1][j]) } if j > 0 { grid[i][j] = min(grid[i][j], grid[i][j - 1]) ans = max(ans, original - grid[i][j - 1]) } } } return ans }