Given a 2 x N grid of integer, A, choose numbers such that the sum of the numbers is maximum and no two chosen numbers are adjacent horizontally, vertically or diagonally, and return it.
Note: You can choose more than 2 numbers.
Input Format:
The first and the only argument of input contains a 2d matrix, A.
Output Format:
Return an integer, representing the maximum possible sum.
Constraints:
1 <= N <= 20000
1 <= A[i] <= 2000
Example:
Input 1:
A = [ [1]
[2] ]
Output 1:
2
Explanation 1:
We will choose 2.
Input 2:
A = [ [1, 2, 3, 4]
[2, 3, 4, 5] ]
Output 2:
We will choose 3 and 5.
Method:
For each column, we choose the biggest number, and then add it with the previous result from Max(col - 1, col - 2)
Solution:
Time: O(n) Space: O(1)
public class Solution { public int adjacent(int[][] A) { if (A == null || A.length == 0) return 0; int prevColOne = 0; int prevColTwo = 0; int colOne = 0; int colTwo = 0; for (int j = 0; j < A[0].length; j ++) { if (j % 2 == 0) { prevColOne = colOne; colOne = Math.max(prevColTwo, colOne) + Math.max(A[0][j], A[1][j]); } else { prevColTwo = colTwo; colTwo = Math.max(prevColOne, colTwo) + Math.max(A[0][j], A[1][j]); } } return Math.max(colOne, colTwo); } }