Skip to content

Commit 1dd97f0

Browse files
authored
Merge pull request #3299 from harshuCodes-git/patch-1
Create 1463. Cherry Pickup II.cpp
2 parents bcafb32 + 6c92efe commit 1dd97f0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

cpp/1463-cherry-pickup-ii.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <vector>
2+
#include <algorithm>
3+
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int cherryPickup(vector<vector<int>>& grid) {
9+
int rows = grid.size();
10+
int cols = grid[0].size();
11+
12+
vector<vector<vector<int>>> dp(rows, vector<vector<int>>(cols, vector<int>(cols, 0)));
13+
14+
for (int i = rows - 1; i >= 0; --i) {
15+
for (int j = 0; j < cols; ++j) {
16+
for (int k = 0; k < cols; ++k) {
17+
int cherries = grid[i][j] + (j != k ? grid[i][k] : 0);
18+
if (i == rows - 1) {
19+
dp[i][j][k] = cherries;
20+
} else {
21+
int maxCherries = 0;
22+
for (int dj = -1; dj <= 1; ++dj) {
23+
for (int dk = -1; dk <= 1; ++dk) {
24+
int nj = j + dj;
25+
int nk = k + dk;
26+
if (nj >= 0 && nj < cols && nk >= 0 && nk < cols) {
27+
maxCherries = max(maxCherries, dp[i + 1][nj][nk]);
28+
}
29+
}
30+
}
31+
dp[i][j][k] = cherries + maxCherries;
32+
}
33+
}
34+
}
35+
}
36+
37+
return dp[0][0][cols - 1];
38+
}
39+
};

0 commit comments

Comments
 (0)