Collect Cherries on an Outward and Return Trip

Quick Overview

Collect Cherries on an Outward and Return Trip. On the square grid, -1 blocks movement, 0 is empty and 1 holds one cherry.

Collect Cherries on an Outward and Return Trip

Company: InMobi

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem On the square grid, -1 blocks movement, 0 is empty and 1 holds one cherry. Travel from the upper-left corner to the lower-right using right/down moves, then return using left/up moves. Each cherry can be collected only once across both trips. Return the maximum collected count, or zero if the corners cannot be connected. ```cpp class Solution { public: int cherryPickup(vector<vector<int>>& grid); }; ``` ### Examples **Example 1:** ```text grid = [[1,1],[1,1]] Output: 4 Explanation: Use opposite edges on the two trips to visit all four cells. ``` **Example 2:** ```text grid = [[0,-1],[-1,1]] Output: 0 Explanation: Both possible first steps are blocked. ``` ### Constraints - The grid is n-by-n with 1 <= n <= 50. - Cells contain only -1, 0 or 1. - Both corner endpoints are unblocked. ### Contract considerations Optimize both trips together; choosing the best outward trip alone can lose the overall optimum. ```hint Read the boundary condition How can two equal-step walkers encode the round trip? ``` ### Boundary reminders Optimize both trips together; choosing the best outward trip alone can lose the overall optimum.

Overview: Collect Cherries on an Outward and Return Trip. On the square grid, -1 blocks movement, 0 is empty and 1 holds one cherry.

InMobi logo
InMobi
Source window: 0–3 months · as of Oct 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

On the square grid, -1 blocks movement, 0 is empty and 1 holds one cherry. Travel from the upper-left corner to the lower-right using right/down moves, then return using left/up moves. Each cherry can be collected only once across both trips. Return the maximum collected count, or zero if the corners cannot be connected.

class Solution {
public:
    int cherryPickup(vector<vector<int>>& grid);
};

Examples

Example 1:

grid = [[1,1],[1,1]]
Output: 4
Explanation: Use opposite edges on the two trips to visit all four cells.

Example 2:

grid = [[0,-1],[-1,1]]
Output: 0
Explanation: Both possible first steps are blocked.

Constraints

  • The grid is n-by-n with 1 <= n <= 50.
  • Cells contain only -1, 0 or 1.
  • Both corner endpoints are unblocked.

Contract considerations

Optimize both trips together; choosing the best outward trip alone can lose the overall optimum.

Boundary reminders

Optimize both trips together; choosing the best outward trip alone can lose the overall optimum.