101 Logo
onenoughtone

Code Implementation

Cherry Pickup II Implementation

Below is the implementation of the cherry pickup ii:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* Find the maximum number of cherries collection using both robots.
* Dynamic Programming (3D) approach.
*
* @param {number[][]} grid - Matrix representing a field of cherries
* @return {number} - Maximum number of cherries
*/
function cherryPickup(grid) {
const rows = grid.length;
const cols = grid[0].length;
// Initialize 3D DP array
const dp = Array(rows).fill().map(() =>
Array(cols).fill().map(() =>
Array(cols).fill(-1)
)
);
// Define recursive function
function dfs(row, col1, col2) {
// Base case: reached the bottom row
if (row === rows) {
return 0;
}
// Check if already computed
if (dp[row][col1][col2] !== -1) {
return dp[row][col1][col2];
}
// Calculate cherries collected at current state
let cherries = grid[row][col1];
if (col1 !== col2) {
cherries += grid[row][col2];
}
// Initialize maximum cherries
let maxCherries = 0;
// Try all possible moves for both robots
for (let d1 = -1; d1 <= 1; d1++) {
for (let d2 = -1; d2 <= 1; d2++) {
const newCol1 = col1 + d1;
const newCol2 = col2 + d2;
// Check if new positions are valid
if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
maxCherries = Math.max(maxCherries, dfs(row + 1, newCol1, newCol2));
}
}
}
// Update DP array
dp[row][col1][col2] = cherries + maxCherries;
return dp[row][col1][col2];
}
return dfs(0, 0, cols - 1);
}
/**
* Find the maximum number of cherries collection using both robots.
* Dynamic Programming (2D) approach.
*
* @param {number[][]} grid - Matrix representing a field of cherries
* @return {number} - Maximum number of cherries
*/
function cherryPickupOptimized(grid) {
const rows = grid.length;
const cols = grid[0].length;
// Initialize DP arrays
let curr = Array(cols).fill().map(() => Array(cols).fill(0));
let next = Array(cols).fill().map(() => Array(cols).fill(0));
// Fill DP arrays from bottom to top
for (let row = rows - 1; row >= 0; row--) {
// Reset current row
for (let col1 = 0; col1 < cols; col1++) {
for (let col2 = 0; col2 < cols; col2++) {
curr[col1][col2] = 0;
}
}
// Calculate maximum cherries for current row
for (let col1 = 0; col1 < cols; col1++) {
for (let col2 = 0; col2 < cols; col2++) {
// Calculate cherries collected at current state
let cherries = grid[row][col1];
if (col1 !== col2) {
cherries += grid[row][col2];
}
// Initialize maximum cherries
let maxCherries = 0;
// Try all possible moves for both robots
for (let d1 = -1; d1 <= 1; d1++) {
for (let d2 = -1; d2 <= 1; d2++) {
const newCol1 = col1 + d1;
const newCol2 = col2 + d2;
// Check if new positions are valid
if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
maxCherries = Math.max(maxCherries, next[newCol1][newCol2]);
}
}
}
// Update current row
curr[col1][col2] = cherries + maxCherries;
}
}
// Swap arrays for next iteration
[curr, next] = [next, curr];
}
return next[0][cols - 1];
}
/**
* Find the maximum number of cherries collection using both robots.
* Dynamic Programming with Memoization approach.
*
* @param {number[][]} grid - Matrix representing a field of cherries
* @return {number} - Maximum number of cherries
*/
function cherryPickupMemoization(grid) {
const rows = grid.length;
const cols = grid[0].length;
// Initialize memoization map
const memo = new Map();
// Define recursive function
function dp(row, col1, col2) {
// Base case: reached the bottom row
if (row === rows) {
return 0;
}
// Create a unique key for the memo map
const key = `${row},${col1},${col2}`;
// Check if already computed
if (memo.has(key)) {
return memo.get(key);
}
// Calculate cherries collected at current state
let cherries = grid[row][col1];
if (col1 !== col2) {
cherries += grid[row][col2];
}
// Initialize maximum cherries
let maxCherries = 0;
// Try all possible moves for both robots
for (let d1 = -1; d1 <= 1; d1++) {
for (let d2 = -1; d2 <= 1; d2++) {
const newCol1 = col1 + d1;
const newCol2 = col2 + d2;
// Check if new positions are valid
if (newCol1 >= 0 && newCol1 < cols && newCol2 >= 0 && newCol2 < cols) {
maxCherries = Math.max(maxCherries, dp(row + 1, newCol1, newCol2));
}
}
}
// Update memoization map
const result = cherries + maxCherries;
memo.set(key, result);
return result;
}
return dp(0, 0, cols - 1);
}
// Test cases
const grid1 = [
[3, 1, 1],
[2, 5, 1],
[1, 5, 5],
[2, 1, 1]
];
console.log(cherryPickup(grid1)); // 24
console.log(cherryPickupOptimized(grid1)); // 24
console.log(cherryPickupMemoization(grid1)); // 24
const grid2 = [
[1, 0, 0, 0, 0, 0, 1],
[2, 0, 0, 0, 0, 3, 0],
[2, 0, 9, 0, 0, 0, 0],
[0, 3, 0, 5, 4, 0, 0],
[1, 0, 2, 3, 0, 0, 6]
];
console.log(cherryPickup(grid2)); // 28
console.log(cherryPickupOptimized(grid2)); // 28
console.log(cherryPickupMemoization(grid2)); // 28

Step-by-Step Explanation

Let's break down the implementation:

  1. Define the State: Define the state as (row, col1, col2), where row is the current row, col1 is the column of robot 1, and col2 is the column of robot 2.
  2. Initialize DP Array: Set up a dynamic programming array to keep track of the maximum cherries that can be collected for each state.
  3. Calculate Cherries: For each state, calculate the cherries collected by both robots, being careful not to double-count when both robots are in the same cell.
  4. Try All Possible Moves: For each state, try all possible moves for both robots (9 combinations in total) and find the maximum cherries that can be collected.
  5. Optimize Space: Optimize the space complexity by using a 2D array instead of a 3D array, as we only need the values from the next row.
ProblemSolutionCode
101 Logo
onenoughtone