← Home

1594. Maximum Non Negative Product in a Matrix

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
DFS + memoizationC++Markdown
159

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1594. Maximum Non Negative Product in a Matrix, the solution in this repository is mainly a DFS + memoization solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: DFS + memoization, dynamic programming.

The notes already sitting in the source point us in the right direction:

  • dfs with memorization

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, dfs_back, maxProductPath.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//dfs with memorization
02//Runtime: 24 ms, faster than 16.04% of C++ online submissions for Maximum Non Negative Product in a Matrix.
03//Memory Usage: 15.1 MB, less than 5.04% of C++ online submissions for Maximum Non Negative Product in a Matrix.
04class Solution {
05public:
06    int m, n;
07    long long maxprod;
08    vector<vector<vector<long long>>> memo;
09    
10    void dfs(vector<vector<int>>& grid, int r, int c, long long prod){
11        prod *= grid[r][c];
12        // cout << r << ", " << c << endl;
13        if(r == m-1 && c == n-1){
14            // cout << prod << endl;
15            maxprod = max(maxprod, prod);
16        }else{
17            if(r+1 < m){
18                dfs(grid, r+1, c, prod);
19            }
20            
21            if(c+1 < n){
22                dfs(grid, r, c+1, prod);
23            }
24        }
25    };
26    
27    vector<long long> dfs_back(vector<vector<int>>& grid, int endr, int endc){
28        // cout << endr << ", " << endc << endl; //", " << pos << endl;
29        if(endr == 0 && endc == 0){
30            return memo[0][0] = {grid[0][0], grid[0][0]};
31        }else if(memo[endr][endc][0] != std::numeric_limits<long long>::lowest()){
32            return memo[endr][endc];
33        }else{
34            long long maxres = std::numeric_limits<long long>::lowest();
35            long long minres = std::numeric_limits<long long>::max();
36            // res = grid[endr][endc];
37            
38            // bool newpos = pos;
39            // if(grid[endr][endc] < 0) newpos = !newpos;
40            
41            bool pos = grid[endr][endc] > 0;
42            if(endr-1 >= 0){
43                vector<long long> ret = dfs_back(grid, endr-1, endc);
44                maxres = max(maxres, pos ? ret[1] * grid[endr][endc] : ret[0] * grid[endr][endc]);
45                minres = min(minres, pos ? ret[0] * grid[endr][endc] : ret[1] * grid[endr][endc]);
46            }
47            if(endc-1 >= 0){
48                vector<long long> ret = dfs_back(grid, endr, endc-1);
49                maxres = max(maxres, pos ? ret[1] * grid[endr][endc] : ret[0] * grid[endr][endc]);
50                minres = min(minres, pos ? ret[0] * grid[endr][endc] : ret[1] * grid[endr][endc]);
51            }
52            
53            return memo[endr][endc] = {minres, maxres};
54        }
55    };
56    
57    int maxProductPath(vector<vector<int>>& grid) {
58        m = grid.size();
59        n = grid[0].size();
60        maxprod = std::numeric_limits<long long>::lowest();
61        memo = vector<vector<vector<long long>>>(m, vector<vector<long long>>(n, vector<long long>(2, std::numeric_limits<long long>::lowest())));
62        
63        int MOD = 1e9 + 7;
64        
65        long long prod = 1LL;
66        // dfs(grid, 0, 0, prod);
67        // if(maxprod < 0) return -1;
68        // return maxprod % MOD;
69        
70        vector<long long> res = dfs_back(grid, m-1, n-1);
71        
72//         for(int i = 0; i < m; ++i){
73//             for(int j = 0; j < n; ++j){
74//                 cout << memo[i][j][0] << " ";
75//             }
76//             cout << endl;
77//         }
78        
79//         for(int i = 0; i < m; ++i){
80//             for(int j = 0; j < n; ++j){
81//                 cout << memo[i][j][1] << " ";
82//             }
83//             cout << endl;
84//         }
85        
86        if(res[1] < 0) return -1;
87        return res[1] % MOD;
88    }
89};
90
91//bottom-up DP
92//https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855082/C%2B%2B-Dynamic-Programming-With-Comments
93//Runtime: 8 ms, faster than 92.88% of C++ online submissions for Maximum Non Negative Product in a Matrix.
94//Memory Usage: 10.7 MB, less than 15.98% of C++ online submissions for Maximum Non Negative Product in a Matrix.
95class Solution {
96public:
97    int maxProductPath(vector<vector<int>>& grid) {
98        int m = grid.size();
99        int n = grid[0].size();
100        int MOD = 1e9 + 7;
101        
102        vector<vector<long long>> mx(m, vector<long long>(n, 0LL));
103        vector<vector<long long>> mn(m, vector<long long>(n, 0LL));
104        
105        //base case
106        mx[0][0] = mn[0][0] = grid[0][0];
107        
108        //in the leftmost column, we only have one choice
109        for(int i = 1; i < m; ++i){
110            mx[i][0] = mn[i][0] = mx[i-1][0] * grid[i][0];
111        }
112        
113        //in the top row, we only have one choice
114        for(int j = 1; j < n; ++j){
115            mx[0][j] = mn[0][j] = mn[0][j-1] * grid[0][j];
116        }
117        
118        for(int i = 1; i < m; ++i){
119            for(int j = 1; j < n; ++j){
120                if(grid[i][j] > 0){
121                    //the product could be negative, so don't MOD here
122                    mx[i][j] = max(mx[i-1][j], mx[i][j-1]) * grid[i][j];
123                    mn[i][j] = min(mn[i-1][j], mn[i][j-1]) * grid[i][j];
124                }else{
125                    mx[i][j] = min(mn[i-1][j], mn[i][j-1]) * grid[i][j];
126                    mn[i][j] = max(mx[i-1][j], mx[i][j-1]) * grid[i][j];
127                }
128            }
129        }
130        
131        return mx[m-1][n-1] < 0LL ? -1 : mx[m-1][n-1] % MOD;
132    }
133};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.