- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 66 lines of C++ from the credited upstream file 3363.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 7 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maxCollectedFruits(vector<vector<int>>& fruits) {4 return getTopLeft(fruits) + getTopRight(fruits) + getBottomLeft(fruits) -5 2 * fruits.back().back();6 }7 8 private:9 int getTopLeft(const vector<vector<int>>& fruits) {10 const int n = fruits.size();11 int res = 0;12 for (int i = 0; i < n; ++i)13 res += fruits[i][i];14 return res;15 }16 17 int getTopRight(const vector<vector<int>>& fruits) {18 const int n = fruits.size();19 20 vector<vector<int>> dp(n, vector<int>(n));21 dp[0][n - 1] = fruits[0][n - 1];22 for (int x = 0; x < n; ++x) {23 for (int y = 0; y < n; ++y) {24 if (x >= y && !(x == n - 1 && y == n - 1))25 continue;26 for (const auto& [dx, dy] :27 vector<pair<int, int>>{{1, -1}, {1, 0}, {1, 1}}) {28 const int i = x - dx;29 const int j = y - dy;30 if (i < 0 || i == n || j < 0 || j == n)31 continue;32 if (i < j && j < n - 1 - i)33 continue;34 dp[x][y] = max(dp[x][y], dp[i][j] + fruits[x][y]);35 }36 }37 }38 39 return dp[n - 1][n - 1];40 }41 42 int getBottomLeft(const vector<vector<int>>& fruits) {43 const int n = fruits.size();44 45 vector<vector<int>> dp(n, vector<int>(n));46 dp[n - 1][0] = fruits[n - 1][0];47 for (int y = 0; y < n; ++y) {48 for (int x = 0; x < n; ++x) {49 if (x <= y && !(x == n - 1 && y == n - 1))50 continue;51 for (const auto& [dx, dy] :52 vector<pair<int, int>>{{-1, 1}, {0, 1}, {1, 1}}) {53 const int i = x - dx;54 const int j = y - dy;55 if (i < 0 || i == n || j < 0 || j == n)56 continue;57 if (j < i && i < n - 1 - j)58 continue;59 dp[x][y] = max(dp[x][y], dp[i][j] + fruits[x][y]);60 }61 }62 }63 return dp[n - 1][n - 1];64 }65};66