leetcode
leetcode 2701 ~ 2750
转角路径的乘积中最多能有几个尾随零

转角路径的乘积中最多能有几个尾随零

难度:

标签:

题目描述

You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.

A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.

The product of a path is defined as the product of all the values in the path.

Return the maximum number of trailing zeros in the product of a cornered path found in grid.

Note:

  • Horizontal movement means moving in either the left or right direction.
  • Vertical movement means moving in either the up or down direction.

 

Example 1:

Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]
Output: 3
Explanation: The grid on the left shows a valid cornered path.
It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.
It can be shown that this is the maximum trailing zeros in the product of a cornered path.

The grid in the middle is not a cornered path as it has more than one turn.
The grid on the right is not a cornered path as it requires a return to a previously visited cell.

Example 2:

Input: grid = [[4,3,2],[7,6,1],[8,8,8]]
Output: 0
Explanation: The grid is shown in the figure above.
There are no cornered paths in the grid that result in a product with a trailing zero.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 105
  • 1 <= m * n <= 105
  • 1 <= grid[i][j] <= 1000

代码结果

运行时间: 1143 ms, 内存: 52.4 MB


解释

方法:

题解通过预处理每个数字的2和5的因子个数,并利用这些预处理的数据来计算二维网格每个位置的累计因子数,最终以此来找出转角路径乘积中尾随零的最大数目。具体步骤为:1. 对所有可能的数字值从2到1000,计算并存储每个数字分解中2和5的个数。2. 为了有效计算乘积的尾随零数目,使用前缀和的方法存储网格中每一行从开始到当前列的2和5的因子的总数。3. 遍历网格的每一列,计算从当前列向左或向右拐弯时2和5的因子总数,使用上述前缀和加速这一计算。4. 从每个网格点考虑所有可能的转角路径(向上、向下、向左、向右),并更新尾随零的最大数目。这种方法有效地利用了动态规划的思想和前缀和技术,避免了重复计算。

时间复杂度:

O(m * n)

空间复杂度:

O(m * n)

代码细节讲解

🦆
在预处理数字的2和5因子时,你是如何确保每个数字的因子被正确计算的?具体的递推逻辑是什么?
在预处理每个数字的2和5的因子时,使用递归的方法来确保每个数字的因子被正确计算。对于数字i,如果它能被2整除,则它的2的因子个数等于`i // 2`的2的因子个数再加1;同理,如果它能被5整除,则它的5的因子个数等于`i // 5`的5的因子个数再加1。通过这种递推方式,可以从小到大依次计算出每个数字的2和5的因子个数,从而确保计算的正确性。
🦆
在处理前缀和数组时,为什么选择使用一个二维数组,并且数组的每个元素都是一个元组来存储2和5的因子数?这种结构的优势在哪里?
使用一个二维数组存储前缀和,并且每个元素是一个元组(存储2和5的因子数),主要是为了方便计算任意子区域中数字的2和5因子的总数。二维数组的每一行代表一个网格行的前缀和,元组中分别记录该行到当前列为止的2和5因子的累计数。这种结构使得在遍历网格并计算转角路径的尾随零时,能够快速获取任意水平或垂直段的2和5因子总数,从而快速计算出尾随零的数量。此外,这种方法避免了重复计算,提高了效率。
🦆
在计算尾随零的最大数目时,如何处理并确保不同方向的转角路径都被考虑到?
在计算尾随零的最大数目时,算法考虑了从每个网格点出发的所有可能的转角路径(包括向上、向下、向左、向右转弯的路径)。通过遍历每一列,分别计算从该列的顶部到底部和从底部到顶部的累积2和5因子的总数,并结合该列对应行的前缀和,计算出从该网格点向左或向右拐弯的2和5因子总数。然后,算法计算并更新可能的最大尾随零数目。这种全方位考虑确保了不同方向的转角路径都被充分计算,从而找出可能的最大尾随零数目。

相关问题