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
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.
Approach:
Very much similar to LIS (Longest Increasing Subsequence) but in this case dp[i] stores max A[0][i], A[1][i] + max(dp[i-2], dp[i-3]) (of course if (i - 3) >= 0 and (i-2) >= 0) because we can't leave more than two blanks in between while choosing.
Problem Solution in C++ Programming Language:
Problem Solution in Java Programming Language:
No comments:
Post a Comment
Please do not enter any spam link in the comment box