Skip to content

Commit 63408c1

Browse files
committed
Add solution #573
1 parent 14096cc commit 63408c1

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,7 @@
554554
567|[Permutation in String](./solutions/0567-permutation-in-string.js)|Medium|
555555
568|[Maximum Vacation Days](./solutions/0568-maximum-vacation-days.js)|Hard|
556556
572|[Subtree of Another Tree](./solutions/0572-subtree-of-another-tree.js)|Easy|
557+
573|[Squirrel Simulation](./solutions/0573-squirrel-simulation.js)|Medium|
557558
575|[Distribute Candies](./solutions/0575-distribute-candies.js)|Easy|
558559
576|[Out of Boundary Paths](./solutions/0576-out-of-boundary-paths.js)|Medium|
559560
581|[Shortest Unsorted Continuous Subarray](./solutions/0581-shortest-unsorted-continuous-subarray.js)|Medium|

solutions/0573-squirrel-simulation.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)