## Amazon Interview Question

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

**Interview Type:**In-Person

Very nice solution!

3 comments:

1. The function should return the value and not expect main to collect it from the queue (exposing the implementation is generally a bad idea)

2. decreasing sum doesn't have any effect because there is no use of sum afterwards

3. you don't really need the queue to solve this (which I guess is why you got the down vote). It adds space complexity and time complexity for the insertions. It would make sense if the question asked for all the sums sorted but all you need here is the maximal value. Just recursively select the son with the maximal sum and return that value plus the root's value.

```
def findMaxPath(a):
maxTotal = 0
i = 0
j = 0
for row in a:
midval = a[i][j]
leftval = rightval = 0
if j > 1:
leftval = a[i][j-1]
if i != 0:
rightval = a[i][j+1]
if midval >= leftval and midval >= rightval:
max = midval
if i > 0:
print("remained at the same column")
else:
print("began journey")
elif leftval >= rightval:
max = leftval
j -= 1
print("walk one step left")
else:
max = rightval
j += 1
print("walk one step right")
maxTotal += max
print(max)
i += 1
print("walk down")
print(maxTotal)
a = [[55], [94,48], [95, 30, 96], [77, 71, 26, 67]]
findMaxPath(a)
```

static class Result {

int value;

}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int n = in.nextInt();

int [][] a = new int[n][n];

for (int i = 0; i < n; i++) {

for (int j=0; j <= i; j++)

a[i][j] = in.nextInt();

}

int k = findMaxSum(a);

System.out.println(k);

}

private static int findMaxSum(int[][] a) {

int n = a.length;

int sum = 0;

Result result = new Result();

findMaxSumHelper(a, 0, 0, sum, result);

return result.value;

}

private static void findMaxSumHelper(int[][] a, int i, int j, int sum, Result result) {

if (i >= a.length) {

if (result.value < sum)

result.value = sum;

return;

}

int origSum = sum + a[i][j];

findMaxSumHelper(a, i+1, j, origSum, result);

findMaxSumHelper(a, i+1, j+1, origSum, result);

}

```
static class Result {
int value;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int [][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j=0; j <= i; j++)
a[i][j] = in.nextInt();
}
int k = findMaxSum(a);
System.out.println(k);
}
private static int findMaxSum(int[][] a) {
int n = a.length;
int sum = 0;
Result result = new Result();
findMaxSumHelper(a, 0, 0, sum, result);
return result.value;
}
private static void findMaxSumHelper(int[][] a, int i, int j, int sum, Result result) {
if (i >= a.length) {
if (result.value < sum)
result.value = sum;
return;
}
int origSum = sum + a[i][j];
findMaxSumHelper(a, i+1, j, origSum, result);
findMaxSumHelper(a, i+1, j+1, origSum, result);
}
```

- Anonymous March 11, 2017