The DP Mistake Most Developers Make
Most developers approach Dynamic Programming by tracking only the maximum value.
It feels natural.
But in some problems… that approach fails.
🧩 The Problem
I was solving:
👉 Maximum Non-Negative Product in a Matrix
You start from (0,0) and can move only right or down.
The goal is to find the path with the maximum non-negative product.
At first glance, it seems simple:
Just track the maximum product path.
That’s exactly what I did.
And it didn’t work.
❌ Why Tracking Only Max Fails
The issue comes from negative numbers.
Because:
Negative × Negative = Positive
This changes everything.
A path that has a very small (negative) value now
can become the maximum later.
So if you only track the maximum…
you lose important information.
💡 The Key Insight
To solve this problem, you must track both:
- ✅ Maximum product
- ✅ Minimum product
Why?
Because:
min × negative → maxmax × negative → min
This is the core idea.
⚙️ Approach
Use Dynamic Programming.
At each cell (i, j):
-
max[i][j]→ maximum product till here -
min[i][j]→ minimum product till here
Transition:
max = max(top_max * val, top_min * val, left_max * val, left_min * val)
min = min(top_max * val, top_min * val, left_max * val, left_min * val)
💻 Java Solution
class Solution {
public int maxProductPath(int[][] grid) {
int m = grid.length, n = grid[0].length;
long[][] max = new long[m][n];
long[][] min = new long[m][n];
max[0][0] = min[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
max[i][0] = min[i][0] = max[i-1][0] * grid[i][0];
}
for (int j = 1; j < n; j++) {
max[0][j] = min[0][j] = max[0][j-1] * grid[0][j];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
long val = grid[i][j];
long a = max[i-1][j] * val;
long b = min[i-1][j] * val;
long c = max[i][j-1] * val;
long d = min[i][j-1] * val;
max[i][j] = Math.max(Math.max(a, b), Math.max(c, d));
min[i][j] = Math.min(Math.min(a, b), Math.min(c, d));
}
}
long result = max[m-1][n-1];
int MOD = 1_000_000_007;
return result < 0 ? -1 : (int)(result % MOD);
}
}
🚨 Edge Case
- If final result is negative → return
-1 - Else return result % (1e9 + 7)
⏱ Complexity
- Time:
O(m × n) - Space:
O(m × n)
🧠 Final Thought
This problem highlights an important idea:
Sometimes your worst path can become your best.
If you're working with multiplication and negative numbers in DP,
always think beyond just the maximum.
✍️ Author
Ishwar Chandra Tiwari
🚀 CodeWithIshwar
Top comments (0)