#3148

Maximum Difference Score in a Grid

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * m * n)
O(m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n)Space O(1)

Instead of checking every possible cell, we can keep track of the minimum value seen so far as we traverse the grid. This allows us to calculate the maximum score in a single pass.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to keep track of the minimum value seen so far.
  2. 2Step 2: Iterate through each cell in the grid.
  3. 3Step 3: For each cell, calculate the score based on the current cell value and the minimum value seen so far.
  4. 4Step 4: Update the maximum score if the current score is higher.
  5. 5Step 5: Update the minimum value if the current cell value is lower.
solution.py11 lines
1def maxDifferenceScore(grid):
2    max_score = float('-inf')
3    min_value = float('inf')
4    m, n = len(grid), len(grid[0])
5    for i in range(m):
6        for j in range(n):
7            min_value = min(min_value, grid[i][j])
8            if i > 0 or j > 0:
9                score = grid[i][j] - min_value
10                max_score = max(max_score, score)
11    return max_score

Complexity note: This complexity is efficient because we only traverse the grid once, keeping track of the minimum value and maximum score simultaneously.

  • 1The maximum score can be derived from the difference between the current cell and the minimum value seen so far.
  • 2Tracking the minimum value as we traverse helps avoid unnecessary comparisons.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.