Problem Description
Given an m x n grid of positive integers, a cornered path is defined as a continuous set of cells that moves in one direction (either horizontally or vertically) and then optionally makes one turn to move in the alternate direction. The product of a path is the multiplication of all numbers in the path. The goal is to find a cornered path whose product has the maximum number of trailing zeros. Trailing zeros are determined by the minimum count of prime factors 2 and 5 in the product.
Key Insights
- The number of trailing zeros in a product equals the minimum of the total exponents of 2 and 5 in its factorization.
- For each grid cell, precompute the count of factors 2 and 5.
- Precompute prefix sums for counts in all four directions (left-to-right, right-to-left, top-to-bottom, and bottom-to-top) to quickly query the sum of counts along any segment.
- Consider each cell as the potential turning point, and then combine prefix sum values in four different L-shaped paths: up+left, up+right, down+left, and down+right.
- Adjust for the overlap at the turning cell (since it gets added twice) by subtracting its own factor counts once.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n) (for storing the factor counts and prefix sums)
Solution
We first preprocess each cell by computing its factor counts for 2 and 5. Then, we build prefix sum matrices for rows and columns separately such that we can quickly sum up counts along any horizontal or vertical segment.
For every cell in the grid considered as a turning point, we compute the total factor counts on the four candidate L-shaped paths:
- Going left then up.
- Going left then down.
- Going right then up.
- Going right then down.
For each candidate, we add the horizontal and vertical segments’ counts (retrieved via the prefix sums) and subtract the turning cell’s double count. We then take the minimum of the two factor counts (2s and 5s) to get the trailing zero count for that path. The maximum trailing zero count across all cells and candidate paths is our answer.