Maximum Number of Points with Cost Problem
Description
LeetCode Problem 1937.
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c_1) and (r + 1, c_2) will subtract abs(c_1 - c_2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
xforx >= 0.-xforx < 0.
Example 1:

Input: points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Example 2:

Input: points = [[1,5],[2,3],[4,2]]
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
Constraints:
m == points.lengthn == points[r].length1 <= m, n <= 10^51 <= m * n <= 10^50 <= points[r][c] <= 10^5
Solution
Approach: Dynamic Programming with Prefix Maxima
Let f[j] be the best score for the rows seen so far when the last pick is in column j. For the next row p, the new value is g[j] = p[j] + max over k of (f[k] - |j - k|).
Checking all k costs O(n) per cell, but the absolute value can be removed by splitting into two cases:
k <= j:f[k] - (j - k) = (f[k] + k) - j, so keep a running maximum off[k] + kwhile scanning from left to right.k >= j:f[k] - (k - j) = (f[k] - k) + j, so keep a running maximum off[k] - kwhile scanning from right to left.
Take the larger of the two for each j. After the last row, the answer is the maximum of f. Scores can reach about 10^10, so use 64-bit integers where the language needs them.
Complexity: O(m * n) time and O(n) space, where m and n are the number of rows and columns.
from math import inf
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
n = len(points[0])
f = points[0][:]
for p in points[1:]:
g = [0] * n
lmx = -inf
for j in range(n):
lmx = max(lmx, f[j] + j)
g[j] = max(g[j], p[j] + lmx - j)
rmx = -inf
for j in range(n - 1, -1, -1):
rmx = max(rmx, f[j] - j)
g[j] = max(g[j], p[j] + rmx + j)
f = g
return max(f)