# 2087. Minimum Cost Homecoming of a Robot in a Grid

• Time: $O(m + n)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public: int minCost(vector& startPos, vector& homePos, vector& rowCosts, vector& colCosts) { int ans = 0; int i = startPos[0]; int j = startPos[1]; int x = homePos[0]; int y = homePos[1]; while (i != x) ans += i < x ? rowCosts[++i] : rowCosts[--i]; while (j != y) ans += j < y ? colCosts[++j] : colCosts[--j]; return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) { int ans = 0; int i = startPos[0]; int j = startPos[1]; int x = homePos[0]; int y = homePos[1]; while (i != x) ans += i < x ? rowCosts[++i] : rowCosts[--i]; while (j != y) ans += j < y ? colCosts[++j] : colCosts[--j]; return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: ans = 0 i, j = startPos x, y = homePos while i != x: i += 1 if i < x else -1 ans += rowCosts[i] while j != y: j += 1 if j < y else -1 ans += colCosts[j] return ans