881. Round Trip Harvest

Hard7.5 points estimatedMatrixDynamic Programming3 hints

An orchard is laid out as a rectangular grid grid. Each cell is either -1 (a fence, impassable) or a non-negative integer, the amount of fruit hanging there. A picker walks from the top-left cell to the bottom-right cell moving only right or down, then walks back to the top-left moving only left or up, using only cells that are not fences.

Whenever the picker stands on a cell the fruit there is collected and the cell becomes empty (0), so a cell visited on both trips pays out only once. Return the largest total amount of fruit that can be collected over the whole round trip. If no complete round trip exists, return 0.

Example 1

Input:
grid = [[0,4,1],[2,0,3],[5,6,0]]
Output:
21
Explanation:

Go right along the top row and down the right column (4 + 1 + 3), then return along the bottom row and up the left column (6 + 5 + 2): every fruit is collected once, 21 in total.

Example 2

Input:
grid = [[1,0,-1,2],[3,5,0,4],[0,-1,7,1]]
Output:
21
Explanation:

Going out through 1, 3, 5, 0, 4, 1 gives 14; coming back through the 7 beside the end cell, then the emptied cells, adds 7 for a total of 21.

Example 3

Input:
grid = [[2,-1],[-1,3]]
Output:
0
Explanation:

Both neighbours of the start are fences, so no trip to the far corner exists and the answer is 0.

Constraints

  • 1 ≤ rows, columns ≤ 50
  • Each cell is -1 or an integer in [0, 20]
  • The first and last cell are never -1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O((R + C) * R^2)
Space
O(R^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…