|
| 1 | +/** |
| 2 | + * 1463. Cherry Pickup II |
| 3 | + * https://leetcode.com/problems/cherry-pickup-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] |
| 7 | + * represents the number of cherries that you can collect from the (i, j) cell. |
| 8 | + * |
| 9 | + * You have two robots that can collect cherries for you: |
| 10 | + * - Robot #1 is located at the top-left corner (0, 0), and |
| 11 | + * - Robot #2 is located at the top-right corner (0, cols - 1). |
| 12 | + * |
| 13 | + * Return the maximum number of cherries collection using both robots by following the rules below: |
| 14 | + * - From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1). |
| 15 | + * - When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty |
| 16 | + * cell. |
| 17 | + * - When both robots stay in the same cell, only one takes the cherries. |
| 18 | + * - Both robots cannot move outside of the grid at any moment. |
| 19 | + * - Both robots should reach the bottom row in grid. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} grid |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var cherryPickup = function(grid) { |
| 27 | + const rows = grid.length; |
| 28 | + const cols = grid[0].length; |
| 29 | + const cache = new Array(rows).fill().map(() => { |
| 30 | + return new Array(cols).fill().map(() => new Array(cols).fill(-1)); |
| 31 | + }); |
| 32 | + |
| 33 | + return Math.max(0, findMaxCherries(0, 0, cols - 1)); |
| 34 | + |
| 35 | + function findMaxCherries(row, col1, col2) { |
| 36 | + if (row === rows || col1 < 0 || col1 >= cols || col2 < 0 || col2 >= cols) { |
| 37 | + return -Infinity; |
| 38 | + } |
| 39 | + if (cache[row][col1][col2] !== -1) { |
| 40 | + return cache[row][col1][col2]; |
| 41 | + } |
| 42 | + |
| 43 | + const cherries = col1 === col2 ? grid[row][col1] : grid[row][col1] + grid[row][col2]; |
| 44 | + |
| 45 | + if (row === rows - 1) { |
| 46 | + return cherries; |
| 47 | + } |
| 48 | + |
| 49 | + let maxCherries = -Infinity; |
| 50 | + for (const nextCol1 of [col1 - 1, col1, col1 + 1]) { |
| 51 | + for (const nextCol2 of [col2 - 1, col2, col2 + 1]) { |
| 52 | + maxCherries = Math.max(maxCherries, findMaxCherries(row + 1, nextCol1, nextCol2)); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + cache[row][col1][col2] = cherries + maxCherries; |
| 57 | + return cache[row][col1][col2]; |
| 58 | + } |
| 59 | +}; |
0 commit comments