|
| 1 | +/** |
| 2 | + * 573. Squirrel Simulation |
| 3 | + * https://leetcode.com/problems/squirrel-simulation/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two integers height and width representing a garden of size height x width. |
| 7 | + * You are also given: |
| 8 | + * - an array tree where tree = [treer, treec] is the position of the tree in the garden, |
| 9 | + * - an array squirrel where squirrel = [squirrelr, squirrelc] is the position of the squirrel |
| 10 | + * in the garden, |
| 11 | + * - and an array nuts where nuts[i] = [nutir, nutic] is the position of the ith nut in the garden. |
| 12 | + * |
| 13 | + * The squirrel can only take at most one nut at one time and can move in four directions: up, down, |
| 14 | + * left, and right, to the adjacent cell. |
| 15 | + * |
| 16 | + * Return the minimal distance for the squirrel to collect all the nuts and put them under the tree |
| 17 | + * one by one. |
| 18 | + * |
| 19 | + * The distance is the number of moves. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} height |
| 24 | + * @param {number} width |
| 25 | + * @param {number[]} tree |
| 26 | + * @param {number[]} squirrel |
| 27 | + * @param {number[][]} nuts |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var minDistance = function(height, width, tree, squirrel, nuts) { |
| 31 | + const helper = (p1, p2) => Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]); |
| 32 | + |
| 33 | + let totalDistance = 0; |
| 34 | + let maxSaving = -Infinity; |
| 35 | + |
| 36 | + for (const nut of nuts) { |
| 37 | + const nutToTree = helper(nut, tree); |
| 38 | + totalDistance += 2 * nutToTree; |
| 39 | + const squirrelToNut = helper(squirrel, nut); |
| 40 | + maxSaving = Math.max(maxSaving, nutToTree - squirrelToNut); |
| 41 | + } |
| 42 | + |
| 43 | + return totalDistance - maxSaving; |
| 44 | +}; |
0 commit comments