7
2
Objective
Find the most expensive path from the top-left of a square grid to the bottom-right such that its total cost is below a given threshold.
Scenario
- You are given a square
NxN
grid. - You are given a maximum cost.
- Every cell in the grid has a cost. The top-left cell has cost
0
. - The cost of a path is the sum of the costs of the cells in the path. Its "cost surplus" is the result of subtracting its cost from the maximum cost.
- Movement is always either right one cell or down one cell.
- The starting point is the top-left cell of the grid and the goal is the bottom-right cell.
- You must output the smallest cost surplus of any path with a non-negative cost surplus, or -1 if there is no such path (The maximum cost is not enough).
Input restrictions
N
will be between 1 and 20 inclusive.- The maximum cost will be between 1 and 200 inclusive.
- The cost of each cell will be between 0 and 10 inclusive.
Examples
Maximum cost: 9
Grid:0 1 5 2 3 2 2 3 2
Expected output: 0
Explanation: there is a path0 2 2 3 2
with cost 9 and cost surplus 0.Maximum cost: 15
Grid:0 1 5 2 3 2 2 3 2
Expected output: 5
Explanation: the most expensive path is0 1 5 2 2
with cost 10 and cost surplus 5.Maximum cost: 6
Grid:0 1 5 2 3 2 2 3 2
Expected output: -1
Explanation: the least expensive path is0 1 3 2 2
with cost 8, which is greater than 6.
@Sp3000 added the code-golf tag! thanks! – Niko Adrianus Yuwono – 2014-12-04T06:22:31.450
@Sp3000 OK so for the first one the maximum number will be down-right-right-down so it will be
9 - (0+2+3+2+2) = 0
and for the second one will be down-right-down-right so it will be15 - (0+2+3+3+2) = 10
– Niko Adrianus Yuwono – 2014-12-04T06:28:35.780@Sp3000 OP basically wants the costliest possible route.. – Optimizer – 2014-12-04T06:29:17.027
@Optimizer That would be more easy to understand then! I already changed the title. – Niko Adrianus Yuwono – 2014-12-04T06:30:39.200
Oh right, sorry I got a little confused as to whether we were minimising or maximising. If that's the case I'm a little confused about the maximum step - is that allowed to go negative? It seems to me that rather than having a maximum step you could just find the path which scores the most "points", so to speak. – Sp3000 – 2014-12-04T06:32:10.893
@Sp3000 No it won't be allowed to be negative. You will need to backtrack if the value goes to negative. – Niko Adrianus Yuwono – 2014-12-04T06:35:09.320
1@Sp3000 steps here are money. Each cell has cost. You can only go right or bottom, so total cells u visit is constant. You go further only when you have money. – Optimizer – 2014-12-04T06:35:34.677
Am I correct to assume that the cost of a path includes both the cost of the top-left cell and the cost of the bottom-right cell? – Peter Taylor – 2014-12-04T09:46:19.057
@PeterTaylor Yes! But let's just assume the top left will always be 0 – Niko Adrianus Yuwono – 2014-12-04T14:57:56.610