Problem Β· Prefix Sum

Minimum Cost to Move Within a Grid (Akuna Shang Hai πŸŒƒ)

Learn this problem
● EasyAkuna CapitalFULLTIMEOA

Problem statement

A player stands on a cell within a grid. The player can move to one of four adjacent cells, but the motion is constrained by lasers. To move from one position to another involves a cost: the cost to move from row i to row i Β± 1 is costRows[i] and the cost to move from column j to column j Β± 1 is costCols[j]. Find the minimum cost to move from a starting point to an ending point within the grid.

Function

minCost(rows: int, cols: int, initR: int, initC: int, finalR: int, finalC: int, costRows: int[], costCols: int[]) β†’ int

Complete the function minCost in the editor below.

minCost has the following parameters:

  1. int rows: the number of rows in the grid
  2. int cols: the number of columns in the grid
  3. int initR: the player's starting row
  4. int initC: the player's starting column
  5. int finalR: the goal's row
  6. int finalC: the goal's column
  7. int costRows[n]: each costRows[i] denotes the cost to move between rows i and i + 1.
  8. int costCols[m]: each costCols[j] denotes the cost to move between columns j and j + 1.

Returns

int: the minimum cost to move from the starting position to the goal

Examples

Example 1

rows = 3cols = 3initR = 0initC = 0finalR = 1finalC = 2costRows = [2, 5]costCols = [6, 1]return = 9

Moving from row 0 to row 1 crosses boundary costRows[0] = 2. Moving from column 0 to column 2 crosses boundaries costing 6 and 1. The total is 2 + 6 + 1 = 9.

Example 2

rows = 4cols = 4initR = 1initC = 2finalR = 3finalC = 3costRows = [1, 2, 3]costCols = [7, 8, 9]return = 14

Moving from row 1 to row 3 costs costRows[1] + costRows[2] = 2 + 3 = 5. Moving from column 2 to column 3 costs costCols[2] = 9. The total is 14.

Constraints

  • 1 ≀ rows, cols ≀ 105
  • 0 ≀ initR, finalR < rows
  • 0 ≀ initC, finalC < cols
  • 0 ≀ costRows[i] ≀ 104 (0 ≀ i < rows-1)
  • 0 ≀ costCols[j] ≀ 104 (0 ≀ j < cols-1)

More Akuna Capital problems

drafts saved locally
public int minCost(int rows, int cols, int initR, int initC, int finalR, int finalC, int[] costRows, int[] costCols) {
    // write your code here
}
rows3
cols3
initR0
initC0
finalR1
finalC2
costRows[2, 5]
costCols[6, 1]
expected9
checking account