Skip to content

Commit a6001d3

Browse files
authoredJan 8, 2022
Create cherry_pickup_ii.cpp
1 parent cc81dd3 commit a6001d3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
 

Diff for: ‎cherry_pickup_ii.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
int dp[71][71][71];
3+
int delta[3] = {0, -1, 1};
4+
5+
bool isNotInRange(int &c1, int &c2, int &m, int &n) {
6+
return c1 < 0 || c2 < 0 || c1 >= n || c2 >= n;
7+
}
8+
9+
int cherryPickupHelper(vector<vector<int>>& grid, int r, int c1, int c2) {
10+
int m = grid.size(), n = grid[0].size();
11+
12+
if(r == m) {
13+
return 0;
14+
}
15+
16+
if(isNotInRange(c1, c2, m, n)) {
17+
return INT_MIN;
18+
}
19+
20+
if(dp[r][c1][c2] != -1) { //memoized call
21+
return dp[r][c1][c2];
22+
}
23+
24+
int currMaxCherryCount = 0;
25+
26+
for(int i = 0; i < 3; ++i) {
27+
for(int j = 0; j < 3; ++j) {
28+
currMaxCherryCount = max(currMaxCherryCount, cherryPickupHelper(grid, r + 1, c1 + delta[i], c2 + delta[j]));
29+
}
30+
}
31+
32+
currMaxCherryCount += (c1 == c2) ? grid[r][c1] : grid[r][c1] + grid[r][c2];
33+
34+
return dp[r][c1][c2] = currMaxCherryCount; //store computation
35+
}
36+
37+
public:
38+
int cherryPickup(vector<vector<int>>& grid) {
39+
40+
//too much of work in this problem!! DP
41+
//both robots move simultaneously (this reduces a dimension in terms of storage for the dp matrix)
42+
//three directions .. max_cherries: 3 * r1 + 3 * r2 => 9 different states
43+
//one edgecase - r1 and r2 at same position, add value of grid only once
44+
//Top Down approach
45+
46+
int m = grid.size();
47+
if(!m) return 0;
48+
49+
int n = grid[0].size();
50+
51+
memset(dp, -1, sizeof dp);
52+
return cherryPickupHelper(grid, 0, 0, n - 1);
53+
}
54+
};
55+

0 commit comments

Comments
 (0)
Please sign in to comment.