Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
Return the maximum number of points you can achieve.
abs(x) is defined as:
x for x >= 0.-x for x < 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 <= 1051 <= m * n <= 1050 <= points[r][c] <= 105Problem summary: 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, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as: x for x >= 0. -x for x < 0.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[1,2,3],[1,5,1],[3,1,1]]
[[1,5],[2,3],[4,2]]
minimum-path-sum)minimize-the-difference-between-target-and-chosen-elements)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1937: Maximum Number of Points with Cost
class Solution {
public long maxPoints(int[][] points) {
int n = points[0].length;
long[] f = new long[n];
final long inf = 1L << 60;
for (int[] p : points) {
long[] g = new long[n];
long lmx = -inf, rmx = -inf;
for (int j = 0; j < n; ++j) {
lmx = Math.max(lmx, f[j] + j);
g[j] = Math.max(g[j], p[j] + lmx - j);
}
for (int j = n - 1; j >= 0; --j) {
rmx = Math.max(rmx, f[j] - j);
g[j] = Math.max(g[j], p[j] + rmx + j);
}
f = g;
}
long ans = 0;
for (long x : f) {
ans = Math.max(ans, x);
}
return ans;
}
}
// Accepted solution for LeetCode #1937: Maximum Number of Points with Cost
func maxPoints(points [][]int) int64 {
n := len(points[0])
const inf int64 = 1e18
f := make([]int64, n)
for _, p := range points {
g := make([]int64, n)
lmx, rmx := -inf, -inf
for j := range p {
lmx = max(lmx, f[j]+int64(j))
g[j] = max(g[j], int64(p[j])+lmx-int64(j))
}
for j := n - 1; j >= 0; j-- {
rmx = max(rmx, f[j]-int64(j))
g[j] = max(g[j], int64(p[j])+rmx+int64(j))
}
f = g
}
return slices.Max(f)
}
# Accepted solution for LeetCode #1937: Maximum Number of Points with Cost
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)
// Accepted solution for LeetCode #1937: Maximum Number of Points with Cost
/**
* [1937] Maximum Number of Points with Cost
*
* 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, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.
* Return the maximum number of points you can achieve.
* abs(x) is defined as:
*
* x for x >= 0.
* -x for x < 0.
*
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-40-26-diagram-drawio-diagrams-net.png" style="width: 300px; height: 300px;" />
* 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/07/12/screenshot-2021-07-12-at-13-42-14-diagram-drawio-diagrams-net.png" style="width: 200px; height: 299px;" />
* 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.length
* n == points[r].length
* 1 <= m, n <= 10^5
* 1 <= m * n <= 10^5
* 0 <= points[r][c] <= 10^5
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/maximum-number-of-points-with-cost/
// discuss: https://leetcode.com/problems/maximum-number-of-points-with-cost/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn max_points(points: Vec<Vec<i32>>) -> i64 {
let mut points = points;
let mut prev = points
.pop()
.unwrap()
.into_iter()
.map(i64::from)
.collect::<Vec<_>>();
while let Some(next) = points.pop() {
prev.iter_mut().rfold(0, |adj, cur| {
*cur = (adj - 1).max(*cur);
*cur
});
prev.iter_mut().zip(next).fold(0, |adj, (cur, next)| {
let new_adj = (adj - 1).max(*cur);
*cur = new_adj + next as i64;
new_adj
});
}
prev.into_iter().max().unwrap()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1937_example_1() {
let points = vec![vec![1, 2, 3], vec![1, 5, 1], vec![3, 1, 1]];
let result = 9;
assert_eq!(Solution::max_points(points), result);
}
#[test]
fn test_1937_example_2() {
let points = vec![vec![1, 5], vec![2, 3], vec![4, 2]];
let result = 11;
assert_eq!(Solution::max_points(points), result);
}
}
// Accepted solution for LeetCode #1937: Maximum Number of Points with Cost
function maxPoints(points: number[][]): number {
const n = points[0].length;
const f: number[] = new Array(n).fill(0);
for (const p of points) {
const g: number[] = new Array(n).fill(0);
let lmx = -Infinity;
let rmx = -Infinity;
for (let j = 0; j < n; ++j) {
lmx = Math.max(lmx, f[j] + j);
g[j] = Math.max(g[j], p[j] + lmx - j);
}
for (let j = n - 1; ~j; --j) {
rmx = Math.max(rmx, f[j] - j);
g[j] = Math.max(g[j], p[j] + rmx + j);
}
f.splice(0, n, ...g);
}
return Math.max(...f);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.