给定尺寸为N * M的整数矩阵mat [] [] ,任务是打印从左上单元格(0,0)到右下单元格(N – 1 )的路径中矩阵元素的最大乘积。 ,M – 1)的给定矩阵。来自任何像元(i,j)的唯一可能移动是(i + 1,j)或(i,j + 1) 。如果最大积为负,则打印“ -1” 。
例子:
Input: mat[][] = [[1, -2, 1], [1, -2, 1], [3, -4, 1]]
Output: 8
Explanation: The path from top left to bottom right with maximum product is (0, 0) → (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) = 1 * 1 * ( -2 ) * ( -4 ) * ( 1 ) = 8.
Therefore, the maximum positive product is 8.
Input: mat[][] = [[-1, -2, -3], [-2, -3, -3], [-3, -3, -2]]
Output: -1
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2). Therefore, print -1.
天真的方法:解决从左上角单元格递归遍历并通过从每个单元格向右和向下移动来生成从左上角到右下角单元格的所有可能路径的最简单方法。查找生成的每个路径的产品,并在其中打印最大路径。
时间复杂度: O(2 max(N,M) )
辅助空间: O(1)
高效方法:为了优化上述方法,其思想是使用动态编程。请按照以下步骤解决问题:
- 初始化矩阵maxPath [] []和minPath [] [] ,分别存储路径的最大和最小乘积。
- 这个想法也是要跟踪到目前为止获得的最大负乘积,因为如果遇到任何负乘积,那么负乘积乘以最大负乘积就可以生成最大正乘积。
- 为了达到索引(i,j),允许的可能移动是向右和向下,因此最大乘积可以是最大乘积或最小乘积,直到第(i – 1,j)个索引或第(i,j – 1)个索引乘以索引(i,j)的元素。
- 完成上述步骤后,如果maxPath [M – 1] [N – 1]的值为非负数,则将其打印为正乘积路径。否则,打印“ -1” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the maximum product
// from the top left and bottom right
// cell of the given matrix grid[][]
int maxProductPath(vector> grid){
// Store dimension of grid
int n = grid.size();
int m = grid[0].size();
// Stores maximum product path
vector> maxPath(n, vector(m, 0));
// Stores minimum product path
vector> minPath(n, vector(m, 0));
// Traverse the grid and update
// maxPath and minPath array
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// Initialize to inf and -inf
int mn = INT_MAX;
int mx = INT_MIN;
// Base Case
if (i == 0 and j == 0)
{
mx = grid[i][j];
mn = grid[i][j];
}
// Calculate for row:
if (i > 0)
{
int tempmx = max((maxPath[i - 1][j] * grid[i][j]),
(minPath[i - 1][j] * grid[i][j]));
// Update the maximum
mx = max(mx, tempmx);
int tempmn = min((maxPath[i - 1][j] * grid[i][j]),
(minPath[i - 1][j] * grid[i][j]));
// Update the minimum
mn = min(mn, tempmn);
}
// Calculate for column:
if (j > 0)
{
int tempmx = max((maxPath[i][j - 1] * grid[i][j]),
(minPath[i][j - 1] * grid[i][j]));
// Update the maximum
mx = max(mx, tempmx);
int tempmn = min((maxPath[i][j - 1] * grid[i][j]),
(minPath[i][j - 1] * grid[i][j]));
// Update the minimum
mn = min(mn, tempmn);
}
// Update maxPath and minPath
maxPath[i][j] = mx;
minPath[i][j] = mn;
}
}
// If negative product
if(maxPath[n - 1][m - 1] < 0)
return -1;
// Otherwise
else
return(maxPath[n - 1][m - 1]);
}
// Driver Code
int main(){
// Given matrix mat[][]
vector> mat = {{1, -2, 1},
{1, -2, 1},
{3, -4, 1}};
// Function Call
cout<<(maxProductPath(mat));
}
// This code is contributed by mohit kumar 29
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to find the maximum product
// from the top left and bottom right
// cell of the given matrix grid[][]
static int maxProductPath(int[][] grid)
{
// Store dimension of grid
int n = grid.length;
int m = grid[0].length;
// Stores maximum product path
int[][] maxPath = new int[n][m];
// Stores minimum product path
int[][] minPath = new int[n][m];
// Traverse the grid and update
// maxPath and minPath array
for(int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// Initialize to inf and -inf
int mn = Integer.MAX_VALUE;
int mx = Integer.MIN_VALUE;
// Base Case
if(i == 0 && j == 0)
{
mx = grid[i][j];
mn = grid[i][j];
}
// Calculate for row:
if(i > 0)
{
int tempmx =Math.max((maxPath[i - 1][j] *
grid[i][j]),(minPath[i - 1][j] *
grid[i][j]));
// Update the maximum
mx = Math.max(mx, tempmx);
int tempmn = Math.min((maxPath[i - 1][j] *
grid[i][j]),(minPath[i - 1][j] *
grid[i][j]));
// Update the minimum
mn=Math.min(mn, tempmn);
}
// Calculate for column
if(j > 0)
{
int tempmx = Math.max((maxPath[i][j - 1] *
grid[i][j]),(minPath[i][j - 1] *
grid[i][j]));
// Update the maximum
mx = Math.max(mx, tempmx);
int tempmn = Math.min((maxPath[i][j - 1] *
grid[i][j]),(minPath[i][j - 1] *
grid[i][j]));
// Update the minimum
mn=Math.min(mn, tempmn);
}
// Update maxPath and minPath
maxPath[i][j] = mx;
minPath[i][j] = mn;
}
}
// If negative product
if(maxPath[n - 1][m - 1] < 0)
{
return -1;
}
// Otherwise
else
{
return(maxPath[n - 1][m - 1]);
}
}
// Driver Code
public static void main (String[] args)
{
// Given matrix mat[][]
int[][] mat = {{1, -2, 1}, {1, -2, 1}, {3, -4, 1}};
// Function Call
System.out.println(maxProductPath(mat));
}
}
// This code is contributed by rag2127
Python3
# Python program for the above approach
# Function to find the maximum product
# from the top left and bottom right
# cell of the given matrix grid[][]
def maxProductPath(grid):
# Store dimension of grid
n, m = len(grid), len(grid[0])
# Stores maximum product path
maxPath = [[0 for i in range(m)] for j in range(n)]
# Stores minimum product path
minPath = [[0 for i in range(m)] for j in range(n)]
# Traverse the grid and update
# maxPath and minPath array
for i in range(n):
for j in range(m):
# Initialize to inf and -inf
mn = float("inf")
mx = float("-inf")
# Base Case
if (i == 0 and j == 0):
mx = grid[i][j]
mn = grid[i][j]
# Calculate for row:
if i > 0:
tempmx = max((maxPath[i - 1][j] * grid[i][j]),
(minPath[i - 1][j] * grid[i][j]))
# Update the maximum
mx = max(mx, tempmx)
tempmn = min((maxPath[i - 1][j] * grid[i][j]),
(minPath[i - 1][j] * grid[i][j]))
# Update the minimum
mn = min(mn, tempmn)
# Calculate for column:
if (j > 0):
tempmx = max((maxPath[i][j - 1] * grid[i][j]),
(minPath[i][j - 1] * grid[i][j]))
# Update the maximum
mx = max(mx, tempmx)
tempmn = min((maxPath[i][j - 1] * grid[i][j]),
(minPath[i][j - 1] * grid[i][j]))
# Update the minimum
mn = min(mn, tempmn)
# Update maxPath and minPath
maxPath[i][j] = mx
minPath[i][j] = mn
# If negative product
if(maxPath[n - 1][m - 1] < 0):
return -1
# Otherwise
else:
return(maxPath[n - 1][m - 1])
# Driver Code
# Given matrix mat[][]
mat = [[1, -2, 1],
[1, -2, 1],
[3, -4, 1]]
# Function Call
print(maxProductPath(mat))
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the maximum product
// from the top left and bottom right
// cell of the given matrix grid[][]
static int maxProductPath(int[,] grid)
{
// Store dimension of grid
int n = grid.GetLength(0);
int m = grid.GetLength(1);
// Stores maximum product path
int[,] maxPath = new int[n, m];
// Stores minimum product path
int[,] minPath = new int[n, m];
// Traverse the grid and update
// maxPath and minPath array
for(int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// Initialize to inf and -inf
int mn = Int32.MaxValue;
int mx = Int32.MinValue;
// Base Case
if(i == 0 && j == 0)
{
mx = grid[i, j];
mn = grid[i, j];
}
// Calculate for row:
if(i > 0)
{
int tempmx = Math.Max((maxPath[i - 1, j] *
grid[i, j]),
(minPath[i - 1, j] *
grid[i, j]));
// Update the maximum
mx = Math.Max(mx, tempmx);
int tempmn = Math.Min((maxPath[i - 1, j] *
grid[i, j]),
(minPath[i - 1, j] *
grid[i, j]));
// Update the minimum
mn = Math.Min(mn, tempmn);
}
// Calculate for column
if(j > 0)
{
int tempmx = Math.Max((maxPath[i, j - 1] *
grid[i, j]),
(minPath[i, j - 1] *
grid[i, j]));
// Update the maximum
mx = Math.Max(mx, tempmx);
int tempmn = Math.Min((maxPath[i, j - 1] *
grid[i, j]),
(minPath[i, j - 1] *
grid[i,j]));
// Update the minimum
mn = Math.Min(mn, tempmn);
}
// Update maxPath and minPath
maxPath[i,j] = mx;
minPath[i,j] = mn;
}
}
// If negative product
if(maxPath[n - 1, m - 1] < 0)
{
return -1;
}
// Otherwise
else
{
return(maxPath[n - 1, m - 1]);
}
}
// Driver Code
static public void Main ()
{
// Given matrix mat[][]
int[,] mat={{1, -2, 1}, {1, -2, 1}, {3, -4, 1}};
// Function Call
Console.WriteLine(maxProductPath(mat));
}
}
// This code is contributed by avanitrachhadiya2155
8
时间复杂度: O(M * N)
辅助空间: O(M * N)