09. Chocolate Pickup II
β GFG solution to the Chocolate Pickup II problem: maximize chocolates collected by a robot traveling to bottom-right and back to top-left using optimal path selection with DP. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a square matrix mat[][] of size n Γ n, where each cell represents either a blocked cell or a cell containing some chocolates. If mat[i][j] equals -1, then the cell is blocked and cannot be visited. Otherwise, mat[i][j] represents the number of chocolates present in that cell.
The task is to determine the maximum number of chocolates a robot can collect by:
Starting from the top-left cell
(0, 0)Moving to the bottom-right cell
(n-1, n-1)Returning back to
(0, 0)
Movement Rules:
Forward journey
(0,0) β (n-1,n-1): Robot can move only right(i, j+1)or down(i+1, j)Return journey
(n-1,n-1) β (0,0): Robot can move only left(i, j-1)or up(i-1, j)
Important: After collecting chocolates from a cell (i, j), that cell becomes empty (mat[i][j] = 0) for the next visit. If there is no valid path for either journey, return 0.
π Examples
Example 1
Input: mat[][] = [[0, 1, -1],
[1, 1, -1],
[1, 1, 2]]
Output: 7
Explanation: Optimal path: (0,0) β (1,0) β (2,0) β (2,1) β (2,2) β (2,1) β (1,1) β (0,1) β (0,0)
Total chocolates = 0 + 1 + 1 + 1 + 2 + 0 + 1 + 1 + 0 = 7Example 2
Example 3
π Constraints
$1 \le n \le 50$
$-1 \le \text{mat}[i][j] \le 100$
β
My Approach
The optimal solution treats this as a simultaneous two-robot path problem using Dynamic Programming with Memoization:
Coordinate Transformation Strategy
Key Insight: Instead of simulating forward and return journeys separately, we can model this as two robots moving simultaneously from
(0,0)to(n-1,n-1).State Representation:
Track robot 1 at position
(i1, j1)and robot 2 at position(i2, j2)Use coordinate transformation: If both robots have moved the same total distance, then
i1 + j1 = i2 + j2This reduces state space to
(i1, j1, j2)wherei2 = i1 + j1 - j2
Movement Transitions:
Each robot has 2 choices at each step: move down or move right
Total combinations: 2 Γ 2 = 4 possible transitions per state
Direction encoding:
d=0means down,d=1means right
Chocolate Collection:
If robots are at the same cell
(i1 == i2 && j1 == j2): collect chocolates only onceIf robots are at different cells: collect from both cells
Base Cases:
If any robot goes out of bounds or hits a blocked cell: return very negative value
If robot 1 reaches
(n-1, m-1)and both robots are at the same position: returnmat[n-1][m-1]
Memoization:
Cache results in 3D DP table
dp[i1][j1][j2]Avoid recomputation of overlapping subproblems
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ mΒ² Γ 4), where n is the number of rows and m is the number of columns. We explore all possible states (i1, j1, j2) and for each state, we try 4 transitions (2 directions for each robot). Each state is computed only once due to memoization.
Expected Auxiliary Space Complexity: O(n Γ mΒ²), as we use a 3D DP table to store memoized results for all possible states of the two robots plus recursion stack space in case of recursive approach.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ Bottom-Up Iterative DP
π‘ Algorithm Steps:
Build 3D DP table iteratively from top to bottom without recursion.
Initialize base case at starting position (0,0,0).
For each state, compute all 4 possible transitions (down/right combinations).
Calculate second robot position using coordinate transformation formula.
Accumulate chocolates ensuring no double-counting when robots meet.
π Complexity Analysis:
Time: β±οΈ O(nΒ·mΒ²Β·4) - Iterate through all states with 4 transition possibilities
Auxiliary Space: πΎ O(nΒ·mΒ²) - 3D DP table storage
β
Why This Approach?
No recursion overhead or stack space usage
Easier to trace and debug state transitions
More intuitive forward-building DP pattern
π 3οΈβ£ Space-Optimized 2D DP
π‘ Algorithm Steps:
Reduce space complexity by maintaining only current and next layer states.
Use two 2D arrays instead of full 3D table for memory efficiency.
Process layer by layer, alternating between arrays.
Each layer depends only on previous layer in diagonal progression.
Extract final result from last computed layer.
π Complexity Analysis:
Time: β±οΈ O(nΒ·mΒ²Β·4) - Same time complexity as 3D approach
Auxiliary Space: πΎ O(mΒ²) - Only two 2D arrays maintained
β
Why This Approach?
Significant memory optimization for large grids
Maintains same time efficiency as full DP
Ideal for memory-constrained competitive programming
π 3οΈβ£ Path Coordinate Transformation
π‘ Algorithm Steps:
Transform problem using diagonal coordinate system for cleaner state representation.
Track robots using (row, col1, col2) instead of separate coordinates.
Use coordinate math to derive second robot position from first.
Apply standard DP with optimized state space traversal.
Handle boundary conditions using coordinate constraints.
π Complexity Analysis:
Time: β±οΈ O(nΒ·mΒ²Β·4) - All unique states computed with transitions
Auxiliary Space: πΎ O(nΒ·mΒ²) - Map storage for sparse state space
β
Why This Approach?
Flexible memoization using map for sparse grids
Clean coordinate transformation logic
Easy to extend for variations of the problem
π 4οΈβ£ Optimized Recursive with Array DP
π‘ Algorithm Steps:
Combine recursion elegance with array-based memoization efficiency.
Pre-allocate DP array for faster access compared to map.
Use -1 as sentinel value to distinguish uncomputed states.
Implement tail-recursive pattern for better compiler optimization.
Cache results at return point for minimal overhead.
π Complexity Analysis:
Time: β±οΈ O(nΒ·mΒ²Β·4) - Memoized recursion with constant time lookups
Auxiliary Space: πΎ O(nΒ·mΒ²) - Fixed-size array allocation
β
Why This Approach?
Faster array access compared to map-based memoization
Pre-allocated memory reduces allocation overhead
Balance between recursion clarity and performance
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ Lambda Recursion
π’ O(nΒ·mΒ²)
π‘ O(nΒ·mΒ²)
π Clean modern C++ syntax
π§ Lambda overhead
π Bottom-Up DP
π’ O(nΒ·mΒ²)
π‘ O(nΒ·mΒ²)
π No recursion overhead
πΎ Full 3D table needed
π Map Memoization
π’ O(nΒ·mΒ²)
π‘ O(nΒ·mΒ²)
β Sparse state handling
π§ Slower map operations
π― Array Memoization
π’ O(nΒ·mΒ²)
π‘ O(nΒ·mΒ²)
π¨ Fastest cache access
π§ Fixed size constraints
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Competitive Programming
π₯ Array Memoization
β β β β β
π Code Readability
π₯ Lambda Recursion
β β β β β
π― Production Code
π₯ Bottom-Up DP
β β β β β
π Interview Practice
π Lambda Recursion
β β β β β
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated