Leetcode 1937. Maximum Number of Points with Cost

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Maximum Number of Points with Cost

2. Solution

解析:Version 1,先假设points[i][j]取最大值的上一行数值位于第j列的左侧或右侧,然后分别求第j列的上一行左侧最大值以及右侧最大值,points[i][j]的最大值为其上一行左侧最大值及右侧最大值中较大的一个与其相加,依次更新矩阵,取最后一行的最大值。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
m = len(points)
n = len(points[0])
left = [0] * n
right = [0] * n
for i in range(1, m):
for k in range(n):
if k == 0:
left[k] = points[i-1][k]
else:
left[k] = max(left[k-1] - 1, points[i-1][k])
for k in range(n - 1, -1, -1):
if k == n - 1:
right[k] = points[i-1][k]
else:
right[k] = max(right[k+1] - 1, points[i-1][k])
for j in range(n):
points[i][j] = points[i][j] + max(left[j], right[j])
return max(points[m-1])

Reference

  1. https://leetcode.com/problems/maximum-number-of-points-with-cost/
如果有收获,可以请我喝杯咖啡!