Q:

Max path with 2D array in java , arbitrary cell to start

I wanted to print the maximum value you can accumulate while moving on the 2D array until you go off the 2D edges. 
Note the user either move to the right or to the button on the 2D array.
For example

so I write the code like the following
public static int find(int[][] A) {
    int[][] solution = new int[A.length][A.length];

    solution[0][0] = A[0][0];
    // fill the first row
    for (int i = 1; i < A.length; i++) {
        solution[0][i] = A[0][i] + solution[0][i - 1];
    }

    // fill the first column
    for (int i = 1; i < A.length; i++) {
        
        solution[i][0] = A[i][0] + solution[i - 1][0];
    }

    // path will be either from top or left, choose which ever is maximum
    int temp=0;
    for (int i = 1; i < A.length; i++) {
        for (int j = 1; j < A.length; j++) {
           // if ((A[i][j]+ Math.max(solution[i - 1][j], solution[i][j - 1])) >A[i][j] )
            solution[i][j] = A[i][j]
                    + Math.max(solution[i - 1][j], solution[i][j - 1]);
                //  else solution[i][j] = A[i][j];
                    
        }
    }
    int temp1 = 0;
    int temp2 =0;
    for(int i=0; i< A.length; i++){
       // System.out.println(" temp1= "+temp1);
        if(solution[i][A.length-1] > temp1) temp1= solution[i][A.length-1];
        //System.out.println(" temp1= "+temp1);
        if(solution[A.length-1][i] > temp2) temp2= solution[A.length-1][i];
       // System.out.println(" temp2= "+temp2);
    }
    for(int i=0; i< A.length; i++){
        for (int j=0; j< A.length;j++){
            System.out.print(solution[i][j]+"\t");
        }
         System.out.println(" ");
    }
    return Math.max(temp1,temp2);
    
}

but it gives me 592 as an output and didn't know where is the problem in my code.

A:

The problem says that maximum value you can accumulate while moving on the 2D array, so the path of maximum sum can start from anywhere and end anywhere.
You should keep maximizing the result at each location (i,j). The maximum at each location can be one of the three below:

The value at the location itself : A[i][j]

The value + the maximum so far when you come from top : d[i-1][j] + A[i][j]

The value + the maximum so far when you come from left : d[i][j-1] + A[i][j]

You have to take the maximum of those three.
Code:
public static int find(int[][] A) {
     int R = A.length;
     int C = A[0].length;
     int[][] d = new int[R+1][C+1];
     int res = Integer.MIN_VALUE;
     for ( int i = 1; i <= R; i++ ) {
       for ( int j = 1; j <= C; j++ ) {
          d[i][j] = Math.max( A[i-1][j-1], Math.max(d[i][j-1] + A[i-1][j-1], d[i-1][j] + A[i-1][j-1]));
          res = Math.max( res, d[i][j]);
       }
     }
     return res;
   }

Output : 603
You can play with this code here

