Cow Pie Treasures

Interview

Time limit1sMemory limit128 MB

Summary
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 NiN_i of gold coins (1≤Ni≤251 \le N_i \le 25), and that count is neatly written on its crust.

The cows arranged the pies in a grid of RR rows and CC columns (1≤R≤C≤1001 \le R \le C \le 100) out in the pasture. You start at the top-left pie, position (row 11, column 11), 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 RR, column CC).

When you step into the next column you may keep the same row or change your row by at most 11: from (r,c)(r, c) you may move to (r−1,c+1)(r-1, c+1), (r,c+1)(r, c+1), or (r+1,c+1)(r+1, c+1). You must never leave the grid, and your path must end at (row RR, column CC). 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 6+4+9+9+6+5+8=476 + 4 + 9 + 9 + 6 + 5 + 8 = 47 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 6+4+9+9+6+8+8=506 + 4 + 9 + 9 + 6 + 8 + 8 = 50 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, RR and CC.
  • Lines 2 through R+1R+1: Each line contains the CC 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.

Examples4

  1. Example 1

    Input
    3 7
    6 5 3 7 9 2 7
    2 4 3 5 6 8 6
    4 9 9 9 1 5 8
    
    Expected output
    50
    
  2. Example 2

    Input
    1 1
    7
    
    Expected output
    7
    
  3. Example 3

    Input
    1 6
    3 1 4 1 5 9
    
    Expected output
    23
    
  4. Example 4

    Input
    2 2
    1 2
    3 4
    
    Expected output
    5