Wednesday, 26 November 2014

There is a N*N integer matrix Arr[N][N]. From the row r and column c, we can go to any of the following three indices: (r+1,c-1), (r+1,c) or (r+1,c+1). Find the maximum sum that can be generated from any path starting from any column in first row

Problem:
There is a N*N integer matrix Arr[N][N]. From the row r and column c, we can go to any of the following three indices:
I.                Arr[ r+1 ][ c-1 ] (valid only if c-1>=0)
II.               Arr[ r+1 ][ c ]
III.              Arr[ r+1 ][ c+1 ] (valid only if c+1<=N-1)
So if we start at any column index on row 0, what is the largest sum of any of the paths till row N-1.
Solution
Solution below is O(n^2) solution. We will update all array entries. Starting from last row and moving till first row. Each array entry will be maximum sum that can be generated when starting from that point. At the end we will find entry in first row that has maximum value.

Pseudo code:
void calculateSum(int[][] a,int n,int row) {
       if(row == n-1) {
           return;
       }
       calculateSum(a,n,row+1);
       for(int j=0;j<n;j++) {
           // calculate a[row][j]
           int max = a[row+1][j];
           if(j-1 >=0 && a[row+1][j-1] > max) {
                 max = a[row+1][j-1];
           }
           if(j+1 <= n-1 && a[row+1][j+1] > max) {
                 max = a[row+1][j+1];
           }
           a[row][j] += max;
        }
 }

void maxSumPath(int[][] a,int n) {
      calculateSum(a,n,0);
      int max = a[0][0];
      for(int j=1;j<n;j++) {
          if(a[0][j] > max)max = a[0][j];
      }
      System.out.println(max);
        

2 comments:

  1. Once can you please exaplin your logic .I think there is a mistake

    ReplyDelete
    Replies
    1. Assume you are at Row i of Array A and you have computed for all A[i+1][j] (taking care of boundaries of course) as maximum sum that can be generated if you start from cell A[i+1][j].

      Now if you traverse row i from column 0 to n-1, at any cell k
      A[i][k] = A[i][k] + max (A[i+1][k-1],A[i+1][k],A[i+1][k+1]) (taking care of boundary conditions again)

      the above equation clearly indicate that to compute A[i][k], you need to compute A[i+1] values, so start from last row, where values would be same as cell value because there is no next row.

      Does this help? Can you explain what mistake you think above approach could have?

      Delete