Approach explained pictorially:
Initial matrix

After first iteration

After second iteration
public class Matrix {
public static void main(String[] args) {
//Taking N = 3, for 3x3 matrix.
int[][] A = {{1,2,3},
{6,4,5},
{9,8,7}};
//Dynamic programming approach.
//Logic is to compute the current maximum sum at any given point in the two-dimensional array.
//Time complexity: O(N^2).
for(int i = 1;i < A.length;i++) {
for(int j = 0;j < A.length; j++) {
if(j == 0) {
A[i][j] = max((A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j+1]));
}
else if(j==A.length - 1) {
A[i][j] = max((A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j-1]));
}
else {
A[i][j] = max((A[i][j] + A[i-1][j-1]),(A[i][j] + A[i-1][j]),(A[i][j] + A[i-1][j+1]));
}
}
}
//The maximum sum is present in the last (N-1)th row. Traverse it to find the maximum sum in O(N) time complexity.
int maxSum = Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
if(maxSum < A[A.length - 1][i]) {
maxSum = A[A.length - 1][i];
}
}
System.out.println(maxSum);
}
//Returns the maximum of the two numbers passed as arguments.
public static int max(int a, int b) {
return a >= b ? a:b;
}
//Returns the maximum of the three numbers passed as arguments.
public static int max(int a, int b, int c) {
int x = (a >= b ? a:b);
return c >= x ? c:x;
}
}
No comments:
Post a Comment