#2088
Count Fertile Pyramids in a Land
HardArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n * max(m, n)) | O(m * n) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
We can use dynamic programming to precompute the maximum height of pyramids and inverse pyramids for each cell, allowing us to count valid plots in linear time. This reduces redundant calculations and speeds up the process significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create two DP arrays: dpPyramid and dpInverse to store maximum heights for pyramids and inverse pyramids respectively.
- 2Step 2: Iterate through the grid to fill dpPyramid from top to bottom and dpInverse from bottom to top.
- 3Step 3: For each cell, calculate the total number of pyramids and inverse pyramids based on the heights stored in the DP arrays.
solution.py23 lines
1def countPyramids(grid):
2 m, n = len(grid), len(grid[0])
3 dpPyramid = [[0] * n for _ in range(m)]
4 dpInverse = [[0] * n for _ in range(m)]
5 count = 0
6
7 for r in range(m):
8 for c in range(n):
9 if grid[r][c] == 1:
10 dpPyramid[r][c] = 1
11 if r > 0:
12 dpPyramid[r][c] += min(dpPyramid[r-1][c-1], dpPyramid[r-1][c])
13 count += dpPyramid[r][c] - 1
14
15 for r in range(m-1, -1, -1):
16 for c in range(n):
17 if grid[r][c] == 1:
18 dpInverse[r][c] = 1
19 if r < m - 1:
20 dpInverse[r][c] += min(dpInverse[r+1][c-1], dpInverse[r+1][c])
21 count += dpInverse[r][c] - 1
22
23 return countℹ
Complexity note: The complexity is linear because we only traverse the grid a fixed number of times to compute the heights, making it efficient compared to the brute force approach.
- 1Dynamic programming can significantly reduce redundant calculations.
- 2Understanding the structure of pyramids and inverse pyramids is crucial for efficient counting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.