Ctrl K

One Cell per Row With a Shift Penalty

Medium
You are given a table grid with m rows and n columns holding non-negative numbers. You must pick exactly one cell in every row, and its number is added to your score. Jumping sideways costs points: if you pick column c1 in row r and column c2 in row r + 1, then |c1 − c2| is subtracted from the score. Return the highest score you can get.
Example 1
grid=[[4, 1, 1], [1, 1, 6], [2, 7, 1]] → 14

Take columns 0, 2 and 1: 4 + 6 + 7 = 17, the penalty is |0 − 2| + |2 − 1| = 3, so the total is 14.

Example 2
grid=[[9, 0, 0, 0], [0, 0, 0, 9]] → 15

Taking both nines costs a penalty of 3: 18 − 3 = 15, which beats 9 and 0 in the same column.

Example 3
grid=[[2], [5], [3]] → 10

There is a single column, so there is no choice: 2 + 5 + 3 = 10.

Constraints
  • 1 ≤ m, n
  • m · n ≤ 10⁵
  • 0 ≤ grid[r][c] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWarehouse Cart Routes MediumCheapest Corner-to-Corner Route MediumLargest Solid Square MediumBest Spot for the Turret MediumSteps to the Nearest Zero Medium
loading Python…
Input
grid=[[4, 1, 1], [1, 1, 6], [2, 7, 1]]
Expected
14

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.