Skip to content

573. Squirrel Simulation 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int minDistance(int height, int width, vector<int>& tree,
                  vector<int>& squirrel, vector<vector<int>>& nuts) {
    int totDist = 0;
    int maxSave = INT_MIN;

    for (const vector<int>& nut : nuts) {
      totDist += dist(nut, tree) * 2;
      maxSave = max(maxSave, dist(nut, tree) - dist(nut, squirrel));
    }

    return totDist - maxSave;
  }

 private:
  int dist(const vector<int>& a, const vector<int>& b) {
    return abs(a[0] - b[0]) + abs(a[1] - b[1]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
    int totDist = 0;
    int maxSave = Integer.MIN_VALUE;

    for (int[] nut : nuts) {
      totDist += dist(nut, tree) * 2;
      maxSave = Math.max(maxSave, dist(nut, tree) - dist(nut, squirrel));
    }

    return totDist - maxSave;
  }

  private int dist(int[] a, int[] b) {
    return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def minDistance(
      self,
      height: int,
      width: int,
      tree: list[int],
      squirrel: list[int],
      nuts: list[list[int]],
  ) -> int:
    def dist(a: list[int], b: list[int]) -> int:
      return abs(a[0] - b[0]) + abs(a[1] - b[1])

    totDist = sum(dist(nut, tree) for nut in nuts) * 2
    maxSave = max(dist(nut, tree) - dist(nut, squirrel) for nut in nuts)
    return totDist - maxSave