Skip to content

Commit fd7a89c

Browse files
Add solution and approach of hard daily problem
1 parent 6427cb1 commit fd7a89c

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
Intuition:
2+
1st try uses recursive DP solution which has large time complexity.
3+
4+
2nd approach is a bottom-up design, an iterative DP version, converted from the 1st one with space optimization by using & tick
5+
6+
Think how to reduce the TC.
7+
8+
Approach:
9+
This is a 3D array named dp used for memoization to store intermediate results of the dynamic programming solution.
10+
11+
int f(int r, int c0, int c1, vector<vector<int>>& grid): This is a recursive function f that calculates the maximum number of cherries that can be picked starting from cell (r, c0) and (r, c1).
12+
13+
ans is initialized based on whether the two pickers are on the same or different cells.
14+
The nested loops iterate over the possible next positions for both pickers and calculate the maximum cherries that can be picked from the next row.
15+
16+
ans += next;
17+
18+
Complexity
19+
Time complexity:
20+
O(row×col2)
21+
22+
Space complexity:
23+
O(70^3)→O(70^2)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
#pragma GCC optimize("O3", "unroll-loops")
5+
class Solution
6+
{
7+
public:
8+
int cherryPickup(vector<vector<int>> &grid)
9+
{
10+
int row = grid.size(), col = grid[0].size();
11+
int dp[2][70][70] = {0};
12+
13+
// base case for the last row
14+
for (int c0 = 0; c0 < col; c0++)
15+
for (int c1 = 0; c1 < col; c1++)
16+
{
17+
dp[(row - 1) & 1][c0][c1] = (c0 != c1) ? grid[row - 1][c0] + grid[row - 1][c1] : grid[row - 1][c0];
18+
}
19+
// DP from r=row-2 to 0
20+
for (int r = row - 2; r >= 0; r--)
21+
{
22+
for (int c0 = 0; c0 < col; c0++)
23+
for (int c1 = 0; c1 < col; c1++)
24+
{
25+
int cherry = (c0 != c1) ? grid[r][c0] + grid[r][c1] : grid[r][c0];
26+
int next = 0;
27+
28+
for (int d0 : {c0 - 1, c0, c0 + 1})
29+
for (int d1 : {c1 - 1, c1, c1 + 1})
30+
{
31+
if (d0 < 0 || d0 >= col || d1 < 0 || d1 >= col)
32+
continue;
33+
next = max(next, dp[(r + 1) & 1][d0][d1]);
34+
}
35+
dp[r & 1][c0][c1] = next + cherry;
36+
}
37+
}
38+
39+
return dp[0][0][col - 1];
40+
}
41+
};
42+
43+
auto init = []()
44+
{
45+
ios::sync_with_stdio(0);
46+
cin.tie(0);
47+
cout.tie(0);
48+
return 'c';
49+
}();

042-11th_feb-[NAME OF QUESTION]/approach-explanation.txt

Whitespace-only changes.

042-11th_feb-[NAME OF QUESTION]/code.cpp

Whitespace-only changes.

0 commit comments

Comments
 (0)