## Amazon Interview Question

SDE-2s**Country:**United States

O(m x n)

```
public int solve(int matrix[][]) {
int minSum = 0;
boolean isAllColumnsCovered = false;
int firstMaxColumnID = 0;
int minDiff = Integer.MAX_VALUE;
int N = matrix.length;
if (N < 1) { return 0; }
int M = matrix[0].length;
if (M < 1) { return 0; }
// 1st traversal
for (int i = 0; i < N; i++) {
int max = 0;
int max2 = 0;
int rowSum = 0;
int maxColumnID = 0;
for (int j = 0; j < M; j++)
{
if (matrix[i][j] > max)
{
if (i == 0)
{
firstMaxColumnID = j;
}
else
{
maxColumnID = j;
}
if (j == 0)
{
max = matrix[i][j];
}
else
{
max2 = max;
max = matrix[i][j];
}
}
else if (matrix[i][j] > max2)
{
max2 = matrix[i][j];
}
rowSum += matrix[i][j];
}
rowSum -= max;
minSum += rowSum;
if (!isAllColumnsCovered) {
if (i > 0 && firstMaxColumnID != maxColumnID) {
isAllColumnsCovered = true;
} else {
// Keep the min diff
if (minDiff > (max - max2)) {
minDiff = max - max2;
}
}
}
}
return minSum + (isAllColumnsCovered ? 0 : minDiff);
}
```

To get minimal sum for a row one needs to throw away the biggest element. So let's find for every i-th row first biggest element FB_i and (for secret reason) second biggest element SB_i.

Next we need to check if all FB_i are from the same column. If that is true then we need to substitute at least one of them. To increase the sum for the smallest amount possible find such i that FB_i - SB_i is minimal.

We also need to show that if we do this change we still use all columns. And we still do, because before the change we had selected n-1 columns m times each and one column 0 times and after the change we select n-2 columns m times each, one column m-1 times and one column one time.

```
public int getMinimumSum(int[][] matrix) {
if (matrix == null) {
throw new IllegalArgumentException("matrix is null");
}
int N = matrix.length;
if (N < 2) {
throw new IllegalArgumentException("Number of rows must be equal or greater than 2");
}
int M = matrix[0].length;
if (M < 1) {
throw new IllegalArgumentException("Number of columns must be equal or greater than 1");
}
int result = 0;
int minDelta = Integer.MAX_VALUE;
boolean[] visitedColumns = new boolean[M];
for (int j=0; j < visitedColumns.length; j++) {
visitedColumns[j] = false;
}
for (int i=0; i < N; i++) {
int currentMaxIndex = 0;
int previousMaxIndex = 0;
for (int j=1; j < M; j++) {
if (matrix[i][j] > matrix[i][currentMaxIndex]) {
result += matrix[i][currentMaxIndex];
visitedColumns[currentMaxIndex] = true;
previousMaxIndex = currentMaxIndex;
currentMaxIndex = j;
} else {
if (previousMaxIndex == currentMaxIndex || matrix[i][j] > matrix[i][previousMaxIndex]) {
previousMaxIndex = j;
}
result += matrix[i][j];
visitedColumns[j] = true;
}
}
int delta = matrix[i][currentMaxIndex] - matrix[i][previousMaxIndex];
if (delta < minDelta) {
minDelta = delta;
}
}
for (boolean visitedColumn : visitedColumns) {
if (!visitedColumn) {
return result + minDelta;
}
}
return result;
}
```

O(m x n) solution

- Anoneemus July 23, 2019