Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 7, 2025 16:43
Show Gist options
  • Save tatsuyax25/8c310d073d3568132b889988bedce6b0 to your computer and use it in GitHub Desktop.
Save tatsuyax25/8c310d073d3568132b889988bedce6b0 to your computer and use it in GitHub Desktop.
There is a game dungeon comprised of n x n rooms arranged in a grid. You are given a 2D array fruits of size n x n, where fruits[i][j] represents the number of fruits in the room (i, j). Three children will play in the game dungeon, with initial pos
/**
* @param {number[][]} fruits - 2D grid representing fruits in each room
* @return {number} - Maximum fruits collected by the three children
*/
var maxCollectedFruits = function(fruits) {
const n = fruits.length;
// Step 1: Sum the main diagonal fruits (child A from top-left to bottom-right)
let diagonalSum = 0;
for (let i = 0; i < n; i++) {
diagonalSum += fruits[i][i];
}
let prevDepth = 0;
// Step 2: Traverse layers from top to bottom-right corner
for (let i = 0; i < n - 1; i++) {
// Determine how many positions are in this layer (depth)
let depth = i < (n - 1) / 2 ? i + 1 : (n - 1) - i;
for (let j = 0; j < depth; j++) {
// maxB: max fruits child B can collect at this step
// maxR: max fruits child C can collect at this step
let maxB = 0, maxR = 0;
// Coordinates for child B (starting from bottom-left)
let bRow = n - 1 - j;
let bCol = i;
// Coordinates for child C (starting from top-right)
let rRow = i;
let rCol = n - 1 - j;
// Check possible previous positions for child B
if (j < depth - 1 || prevDepth >= depth) {
maxB = Math.max(maxB, fruits[bRow][i - 1]); // left
maxR = Math.max(maxR, fruits[i - 1][rCol]); // up
}
if (
j < depth - 2 || prevDepth > depth ||
(j < depth - 1 && prevDepth >= depth)
) {
maxB = Math.max(maxB, fruits[bRow - 1][i - 1]); // up-left
maxR = Math.max(maxR, fruits[i - 1][rCol - 1]); // up-left
}
if (j > 0) {
maxB = Math.max(maxB, fruits[bRow + 1][i - 1]); // down-left
maxR = Math.max(maxR, fruits[i - 1][rCol + 1]); // up-right
}
// Add the best previous fruit path to current cell
fruits[bRow][bCol] += maxB;
fruits[rRow][rCol] += maxR;
}
prevDepth = depth;
}
// Step 3: Add final two adjacent cells to bottom-right
// These are the last steps for child B and child C
return diagonalSum + fruits[n - 2][n - 1] + fruits[n - 1][n - 2];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment