Maximum Sum basic#5854

Maximum Sum basic (Editoriale)

Let be the input table. Let dp[i][j] represent the maximum sum of numbers along a path from any cell in the first row to the cell . Then

dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j], dp[i - 1][j + 1]) + a[i][j]

To correctly calculate the values in the first and last columns, set

dp[i][0] = dp[i][m + 1] = -∞

Initialize the first row of the array with the values from the first row of the table :

dp[1][i] = a[1][i], 1 ≤ i ≤ m

The answer to the problem will be the maximum value in the last (-th) row of the array.

Example

Consider the input example.

Algorithm implementation

Declare a constant to store the minimum value, as well as arrays and .

#define MAX 202
#define MIN -2000000000
int a[MAX][MAX], dp[MAX][MAX];

Read the input data. The top-left corner of the table will be stored in . Fill the columns with indices and m + 1 in the array with the minimum possible value .

scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++)
{
  dp[i][0] = dp[i][m + 1] = MIN;
  for (j = 1; j <= m; j++)
    scanf("%d", &a[i][j]);
}

Copy the first row of array into the array .

for (i = 1; i <= n; i++)
  dp[1][i] = a[1][i];

Recalculate the maximum sums along paths from the top row to the cell and store them in the array .

for (i = 2; i <= n; i++)
for (j = 1; j <= m; j++)
  dp[i][j] = max(max(dp[i - 1][j - 1], dp[i - 1][j]), 
                     dp[i - 1][j + 1]) + a[i][j];

Find the largest number in the last (-th) row of the array.

res = MIN;
for (i = 1; i <= m; i++)
  if (dp[n][i] > res) res = dp[n][i];

Print the answer.

printf("%d\n", res);

Java implementation

import java.util.*;

public class Main
{
  static int a[][], dp[][];
  final static int MIN = -2000000000;
  
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m = con.nextInt();
    dp = new int[n+1][m+2];
    a = new int[n+1][m+2];
    
    for (int i = 1; i <= n; i++)
    {
      dp[i][0] = dp[i][m + 1] = MIN;
      for (int j = 1; j <= m; j++)
        a[i][j] = con.nextInt();;
    }
    
    for (int i = 1; i <= m; i++)
      dp[1][i] = a[1][i];
    
    for (int i = 2; i <= n; i++)
    for (int j = 1; j <= m; j++)
      dp[i][j] = Math.max(Math.max(dp[i - 1][j - 1], dp[i - 1][j]), dp[i - 1][j + 1]) + a[i][j];

    int res = MIN;
    for (int i = 1; i <= m; i++)
      if (dp[n][i] > res) res = dp[n][i];
    
    System.out.println(res);
    con.close();
  }
}