I recently gave interview at a company and was rejected in final round having only one problem.
The interviewer stated a 2D-array of n*m length. We can traverse left right top down as well as both diagonally. A fixed window k was provided to find maximum sum of 1d array window traversing any of the way.
The array is not sorted and doesn't have any pattern. No overlapping/rolling is possible at edges.
1<=n,m<=10^5
Example:- 2 3 4 5 2
3 1 8 9 9
4 4 3 2 8
3 4 7 7 7
n=4
m=5
k=3
Output :- Max Sum= 26
Explanations:- (8+9+9)
second row has the largest sum window with size 3.
I gave the brute force approach for traversing all directions(8) along with sliding window approach to calculate the max sum.
Unfortunately I was rejected and I still don't find the optimized solution for the problem made by the interviewer.
My code that I made-
(ignore the inputs required)
class sliding {
public static void main(int ar[][], int k) {
int m = ar.length;
int n = ar[0].length;
int sum = 0;
if (m >= k) { //for row-wise max window
for (int i = 0; i < m; i++) {
int tempSum = 0;
int x = 0;
int j = 0;
while (j < n) {
tempSum += ar[i][j];
if (j - x + 1 < k)
j++;
else if (j - x + 1 == k) {
sum = Math.max(tempSum, sum);
tempSum = tempSum - ar[i][x];
x++;
j++;
}
}
}
}
if (n >= k) //for column-wise max window
{
for (int i = 0; i < n; i++) {
int tempSum = 0;
int x = 0;
int j = 0;
while (j < m) {
tempSum += ar[i]][j];
if (j - x + 1 < k)
j++;
else if (j - x + 1 == k) {
sum = Math.max(tempSum, sum);
temSum = tempSum - ar[i][x];
x++;
j++;
}
}
}
}
//for diagonal-wise max
if (n >= k && m >= k) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int x = 0;
int p = i;
int q = j;
int p_initial = p;
int q_initial = q;
int tempSum = 0;
while (p <= m - k && q <= n - k) {
if (x < k) {
tempSum += ar[p++][q++];
x++;
} else if (x == k) {
sum = Math.max(tempSum, sum);
tempSum -= ar[p_initial][q_initial];
p_initial++;
q_initial++;
}
}
}
}
}
}// sum variable will store the final answer
Complexity - O(n^3)
Can someone optimize my approach or give better solution.