-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0573-squirrel-simulation.js
More file actions
38 lines (31 loc) · 1.16 KB
/
0573-squirrel-simulation.js
File metadata and controls
38 lines (31 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Squirrel Simulation
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var minDistance = function (height, width, tree, squirrel, nuts) {
const calculateManhattanDistance = (firstPoint, secondPoint) => {
const firstCoordinateDifference = Math.abs(firstPoint[0] - secondPoint[0]);
const secondCoordinateDifference = Math.abs(firstPoint[1] - secondPoint[1]);
return firstCoordinateDifference + secondCoordinateDifference;
};
let overallPathDistance = 0;
let maximalBenefit = -Infinity;
const totalNutCount = nuts.length;
for (let nutIterator = 0; nutIterator < totalNutCount; ++nutIterator) {
const currentNutLocation = nuts[nutIterator];
const distanceNutToTree = calculateManhattanDistance(
currentNutLocation,
tree,
);
overallPathDistance += 2 * distanceNutToTree;
const distanceSquirrelToNut = calculateManhattanDistance(
squirrel,
currentNutLocation,
);
const currentIterationGain = distanceNutToTree - distanceSquirrelToNut;
maximalBenefit = Math.max(maximalBenefit, currentIterationGain);
}
const resultDistance = overallPathDistance - maximalBenefit;
return resultDistance;
};