Maximum Number of Points with Cost

Hard

Topics
ArrayDynamic ProgrammingMatrix

You are given an m x n matrix points. You pick exactly one cell in each row. Picking cell (r, c) adds points[r][c] to your score, but for adjacent rows you lose abs(c1 - c2) for the columns picked. Return the maximum score obtainable.

Example 1

012311512311012
One cell is chosen per row and the score is the sum of their values minus the column distance between consecutive picks. The shaded picks score 9. The naive version compares every pair of columns per row; a running left-to-right and right-to-left maximum collapses that to linear.
2D grid — one row per line.
Input:  points = [[1,2,3],[1,5,1],[3,1,1]]
Output: 9

Example 2

01512324201
Input:  points = [[1,5],[2,3],[4,2]]
Output: 11

Constraints

  • m == points.length
  • n == points[i].length
  • 1 <= m, n <= 10^5
  • 1 <= m*n <= 10^5
  • 0 <= points[r][c] <= 10^5.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Row by row, the state is which column you picked, so best[c] is the highest score achievable having chosen column c in the current row. The transition is best_new[c] = points[r][c] + max over c' of (best_old[c'] - |c - c'|).

Written directly that inner maximum costs O(n) per cell, so O(m·n²) overall — at the stated bound of m·n <= 10⁵ with a row of 10⁵ that is 10¹⁰ operations. The trick is to split the absolute value. For c' <= c the penalty is c - c', so the quantity to maximise is best_old[c'] + c' — a prefix maximum. For c' >= c it is best_old[c'] - c', a suffix maximum.

The shown code expresses both as a single running value that decays by one per step: running = max(running - 1, best[c]) sweeping left to right, and again right to left. That is the same prefix/suffix maximum with the ±c folded in, and it is why the whole row costs O(n).

Approach

  1. Start best as the first row.
  2. For each later row, sweep left to right maintaining left[c] = max(left[c-1] - 1, best[c]).
  3. Sweep right to left maintaining right[c] = max(right[c+1] - 1, best[c]).
  4. Set best[c] = points[r][c] + max(left[c], right[c]).
  5. The answer is the largest entry of the final row.

Dry Run

points = [[1,2,3],
          [1,5,1],
          [3,1,1]]

row 0   best = [1, 2, 3]

row 1
  left  sweep: [1, 2, 3]        running = max(running - 1, best[c])
  right sweep: [1, 2, 3]
  best = [1+1, 5+2, 1+3] = [2, 7, 4]

row 2
  left  sweep: [2, 7, 6]        at column 2, 7-1 = 6 beats best[2] = 4
  right sweep: [6, 7, 4]        at column 0, 7-1 = 6 beats best[0] = 2
  best = [3 + max(2,6), 1 + max(7,7), 1 + max(6,4)] = [9, 8, 7]

answer 9

column 0 of row 2 is reached from column 1 of row 1: score 7 minus one unit of
travel, which beats staying in column 0 and its score of 2.

Complexity

  • Time — O(m·n): three linear sweeps per row. Measured: a 100×1000 grid in 0.02s.
  • Space — O(n): three rows of working arrays, with only the previous row retained. The natural m × n table is unnecessary because each row reads only its predecessor.

Common Pitfalls

  • Computing the inner maximum directly, which is O(m·n²). At a single row of 10⁵ columns that is the difference between finishing and not.
  • Doing only the left-to-right sweep. The penalty is symmetric, so a column can be best served by a predecessor on either side; one sweep silently answers a one-directional version of the problem.
  • Initialising the running value to 0 rather than negative infinity, which pretends column −1 is available with score 0.
  • Decaying by one after taking the maximum instead of before. The order max(running - 1, best[c]) is what charges exactly one unit per column of travel.
  • Using floating point without checking the range. The shown solution does, and it is safe: the largest reachable score is about 10¹⁰, well inside the 2⁵³ range where float64 represents integers exactly — verified at 10,000,000 on a 100×1000 all-maximum grid. Integers would be the cleaner choice regardless.
  • Assuming the grid is square. The bound is on m·n, so one dimension can be 10⁵ and the other 1.

Full Solution — all languages

class Solution:
    def maxPoints(self, grid):
        rows, cols = len(grid), len(grid[0])
        best = [float(v) for v in grid[0]]
        for r in range(1, rows):
            left = [0.0] * cols
            right = [0.0] * cols
            running = float('-inf')
            for c in range(cols):
                running = max(running - 1, best[c])
                left[c] = running
            running = float('-inf')
            for c in range(cols - 1, -1, -1):
                running = max(running - 1, best[c])
                right[c] = running
            best = [grid[r][c] + max(left[c], right[c]) for c in range(cols)]
        return int(max(best))
SensAI
Beta
Tap the mic to stop voice mode