Coin Collection
A new online game is gaining popularity. It is based on a matrix of size 2 x n (2 rows and n columns) where a cell formed by the ith row and jth column initially contains coins[i][j] number of coins. The number of coins in each cell is increasing over time. More precisely, at some time k, the number of coins in the cell(i, j) is k * coins[i][j].
A player has to start from the point (0, 0) at time t = 0 and in a single unit of time is allowed to move to any neighboring cell. A player collects all the coins in the cell they visit and each cell must be visited exactly once. Given the initial number of coins in the matrix, coins, find the maximum possible number of coins that a player can collect.
Example:
Suppose n = 4, coins = [[1, 4, 3, 2], [2, 1, 3, 2]]. The optimal path is described below:
Time 0, Cell (0, 0), Coins: 0 Time 1, Cell (1, 0), Coins: 1 * 2 = 2 Time 2, Cell (1, 1), Coins: 2 * 1 = 2 Time 3, Cell (1, 2), Coins: 3 * 3 = 9 Time 4, Cell (1, 3), Coins: 4 * 2 = 8 Time 5, Cell (0, 3), Coins: 5 * 2 = 10 Time 6, Cell (0, 2), Coins: 6 * 3 = 18
Function Description
Complete the function getMaxCoins that has the parameter: int coins[n][2]: the initial number of coins in the matrix.
Returns: long: the maximum total number of coins that can be collected.
Constraints
1 <= n <= 10^5 1 <= coins[i][j] <= 10^5
Here is one approach to solve this problem of finding the maximum coins a player can collect from a 2 x n matrix where the number of coins in each cell increases over time:
|
|
The key ideas are:
- Use a min heap to get next cell with minimum coins
- Keep accumulating coins collected at each cell
- Check and enqueue unvisited neighboring cells
- Return total coins after full traversal
This allows always moving to the next cell with lowest coins but highest rate of increase, optimizing total coins collected.