The Triangle

Time limit2sMemory limit128 MB

Summary
Given a triangular grid of values, find the sub-triangle (either orientation, side at least K) whose truncated average is largest.
Level

Hard8 of 10

Topics
Binary search, Prefix sum, Dynamic programming, Brute force
Solved
No attempts yet

Problem

Farmer John has given Bessie a triangular grid with NN rows (1≤N≤7001 \le N \le 700). Row ii contains ii integers; the jj-th integer of row ii is vi,jv_{i,j} (−109≤vi,j≤109-10^9 \le v_{i,j} \le 10^9, 1≤j≤i1 \le j \le i).

Bessie must choose a sub-triangle whose side length is at least KK (1≤K≤201 \le K \le 20, K≤NK \le N). A sub-triangle is again a triangular block of the grid. It may point the same way as the whole grid (a single top cell that widens by one cell per row going down), or it may be upside down (a full top row that narrows by one cell per row until it ends in a single bottom cell). A sub-triangle of side length ss contains s(s+1)/2s(s+1)/2 cells.

For the example grid with N=3N = 3

    / \
   / 5 \
  /-8  4\
 / 2 -3 6\
 ---------

the two orientations of a side-2 sub-triangle look like this (upward on the left, upside down on the right).

   / 5 \           -8  4
  /-8  4\           \-3/
                     \/

Farmer John takes the average of all numbers in the chosen sub-triangle, discards the digits after the decimal point (truncating toward zero, so the value keeps its sign), and gives Bessie that many gold coins — or takes that many away if the value is negative.

For instance, with K=2K = 2 the best sub-triangle of the grid above has average (4+6−3)/3=2.333…(4 + 6 - 3)/3 = 2.333\ldots, which truncates to 22.

Help Bessie find the maximum number of coins she can obtain over all valid sub-triangles.

Input

  • Line 1: two space-separated integers NN and KK.
  • Lines 2 to N+1N+1: line i+1i+1 contains ii space-separated integers vi,1,vi,2,…,vi,iv_{i,1}, v_{i,2}, \ldots, v_{i,i}.

Output

  • A single line containing the maximum number of coins Bessie can obtain. This value may be negative (the smallest loss she can guarantee).

Examples3

  1. Example 1

    Input
    3 2
    5
    -8 4
    2 -3 6
    
    Expected output
    2
    
  2. Example 2

    Input
    3 1
    1
    2 3
    4 5 6
    
    Expected output
    6
    
  3. Example 3

    Input
    3 3
    5
    -8 4
    2 -3 6
    
    Expected output
    1