Maximum Product in Matrix
Last updated
Last updated
Given a 2D matrix find the path with the maximum product. Make the simplifying assumption that the elements are always positive. Return both the maximum product, and the path (the elements that produce this product). As shown in the table below, an available path for an element is defined by it's 3 or 2 closest elements below it,. Discuss how you would approach with problem with negative elements allowed.
left | center | right | ||||||
[r, c] | [r,c] | [r,c] | ||||||
[r+1,c] | [r+1, c+1] | [r+1,c-1] | [r+1,c] | [r+1,c+1] | [r+1, c-1] | [r+1,c] |
The Idea: See seam carving with dynamic programming, the idea is effectively the same.
Complexity: O(n*m) time and space
Dealing with Negatives:
Negatives can be treated the way as positives. If within out dp algorithm, we look at the absolute distance between neighbors, all the needs to have to negatives is for the value to be unnegated in the end.
Not sure, but one possibility might be to run the algorithm twice. Once, as we've done now, and a second time around that uses absolute value. Select the matrix that returns the maximum value on the bottom row.