Largest Plus Sign — LeetCode 764 Python Solution
MediumArrayDynamic Programming
- Problem
- #764
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines.
Example
- Input
- n = 5, mines = [[4,2]]
- Output
- 2
- Explanation
- In the above grid, the largest plus sign can only be of order 2. One of them is shown.
Python solution
Python
class Solution:
def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
dp = [[n] * n for _ in range(n)]
for x, y in mines:
dp[x][y] = 0
for i in range(n):
left = right = up = down = 0
for j, k in zip(range(n), reversed(range(n))):
left = left + 1 if dp[i][j] else 0
right = right + 1 if dp[i][k] else 0
up = up + 1 if dp[j][i] else 0
down = down + 1 if dp[k][i] else 0
dp[i][j] = min(dp[i][j], left)
dp[i][k] = min(dp[i][k], right)
dp[j][i] = min(dp[j][i], up)
dp[k][i] = min(dp[k][i], down)
return max(max(v) for v in dp)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 764. Largest Plus Sign is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 764. Largest Plus Sign?
- LeetCode 764. Largest Plus Sign is rated Medium on LeetCode.
- What topics does LeetCode 764. Largest Plus Sign cover?
- LeetCode 764. Largest Plus Sign is tagged Array and Dynamic Programming on LeetCode.