Cow Pie Treasures
InterviewTime limit1sMemory limit128 MB
Given an R by C grid of coin counts, find the maximum sum collected moving right one column each step, changing row by at most one, starting at (1,1) and ending at (R,C).
- Level
Medium4 of 10
- Topics
- Dynamic programming, Matrix
- Solved
- No attempts yet
Problem
The cows have been busily baking pies stuffed with gold coins! Each pie holds some number of gold coins (), and that count is neatly written on its crust.
The cows arranged the pies in a grid of rows and columns () out in the pasture. You start at the top-left pie, position (row , column ), and immediately collect its coins. You must travel to the far side of the pasture, moving exactly one column to the right on every step, and you must finish at position (row , column ).
When you step into the next column you may keep the same row or change your row by at most : from you may move to , , or . You must never leave the grid, and your path must end at (row , column ). Every pie you land on adds its coins to your total.
Given the pasture, what is the greatest number of gold coins you can gather?
For example, consider this pasture:
6 5 3 7 9 2 7
2 4 3 5 6 8 6
4 9 9 9 1 5 8
The path below collects coins:
start-> 6 5 3 7 9 2 7
\
2 4 3 5 6 8 6
\ / \
4 9 9-9 1 5-8 <-end
The next path is even better, collecting coins, which is the most possible:
start-> 6 5 3 7 9 2 7
\
2 4 3 5 6-8 6
\ / \
4 9 9-9 1 5 8 <-end
Input
- Line 1: Two space-separated integers, and .
- Lines 2 through : Each line contains the coin counts of that row, space-separated and in order.
Output
- Line 1: A single integer, the maximum number of gold coins that can be gathered.