Given a 2 x N grid of integers A (two rows and N columns), choose a set of elements with maximum possible sum such that no two selected elements are adjacent horizontally, vertically or diagonally.
Example
1
2
3
4
5
Input:
A = [[1,2,3,4],
[2,3,4,5]]
One optimal selection: pick 3 (row0,col2) and 5 (row1,col3) => sum = 8
For each column i you’re never going to pick both elements in the same column because they are vertically adjacent. So the only sensible contribution from column i is the larger of the two values: colMax[i] = max(A[0][i], A[1][i]). Once reduced to the array colMax, the adjacency constraint between columns forbids selecting adjacent columns β this is exactly the classic House Robber problem.
classSolution {
public:longlong maxSum2xN(const std::vector<std::vector<longlong>>& A) {
int n = A[0].size();
if (n ==0) return0;
std::vector<longlong> colMax(n);
for (int i =0; i < n; ++i) colMax[i] = std::max(A[0][i], A[1][i]);
longlong incl =0; // max sum including previous
longlong excl =0; // max sum excluding previous
for (int i =0; i < n; ++i) {
longlong new_excl = std::max(excl, incl);
incl = excl + colMax[i];
excl = new_excl;
}
return std::max(excl, incl);
}
};
classSolution {
publiclongmaxSum2xN(long[][] A) {
int n = A[0].length;
if (n == 0) return 0;
long[] colMax =newlong[n];
for (int i = 0; i < n; ++i) colMax[i]= Math.max(A[0][i], A[1][i]);
long incl = 0L, excl = 0L;
for (int i = 0; i < n; ++i) {
long newExcl = Math.max(excl, incl);
incl = excl + colMax[i];
excl = newExcl;
}
return Math.max(excl, incl);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmax_sum_2xN(self, A: list[list[int]]) -> int:
n = len(A[0])
if n ==0:
return0 col_max = [max(A[0][i], A[1][i]) for i in range(n)]
incl =0# best including previous column excl =0# best excluding previous columnfor v in col_max:
new_excl = excl if excl > incl else incl
incl = excl + v
excl = new_excl
return excl if excl > incl else incl
Instead of creating colMax, directly process each column and maintain two values: incl (best sum including current column) and excl (best sum excluding current column). For a column i, including it contributes max(A[0][i], A[1][i]) plus the previous excl value.