#2245
Maximum Trailing Zeros in a Cornered Path
MediumArrayMatrixPrefix SumPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n * (m + n)) | O(m * n²) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n²)Space O(m * n)
To optimize, we can precompute the number of factors of 2 and 5 for each cell. This allows us to quickly calculate the number of trailing zeros for any cornered path without recalculating products.
⚙️
Algorithm
3 steps- 1Step 1: Create two matrices to store the count of factors of 2 and 5 for each cell in the grid.
- 2Step 2: For each cell, calculate the cumulative sum of factors of 2 and 5 in both horizontal and vertical directions.
- 3Step 3: Iterate through each cell, and for each possible cornered path, compute the number of trailing zeros using the precomputed matrices.
solution.py29 lines
1def count_factors(n, factor):
2 count = 0
3 while n > 0 and n % factor == 0:
4 count += 1
5 n //= factor
6 return count
7
8def max_trailing_zeros(grid):
9 m, n = len(grid), len(grid[0])
10 count2 = [[0] * n for _ in range(m)]
11 count5 = [[0] * n for _ in range(m)]
12
13 for i in range(m):
14 for j in range(n):
15 count2[i][j] = count_factors(grid[i][j], 2)
16 count5[i][j] = count_factors(grid[i][j], 5)
17
18 max_zeros = 0
19 for i in range(m):
20 for j in range(n):
21 for k in range(j, n): # horizontal path
22 zeros2 = sum(count2[i][x] for x in range(j, k + 1))
23 zeros5 = sum(count5[i][x] for x in range(j, k + 1))
24 max_zeros = max(max_zeros, min(zeros2, zeros5))
25 for l in range(i + 1, m): # vertical path
26 zeros2 += count2[l][k]
27 zeros5 += count5[l][k]
28 max_zeros = max(max_zeros, min(zeros2, zeros5))
29 return max_zerosℹ
Complexity note: The time complexity is O(m * n²) because for each cell, we may iterate through all columns in the worst case. The space complexity is O(m * n) due to the storage of the factor counts.
- 1Trailing zeros depend on the minimum of the count of factors of 2 and 5.
- 2Precomputation of factors allows for faster calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.