Skip to content
Advertisement

Finding the coordinates of max sum path in matrix

I have this method which returns the max sum of the path from top left to bottom right (can move only to the right or bottom).

JavaScript

output : 1 + 3 + 4 + 5 = 13

But what I want to get is also the coordinates of the points of the path: [(0,0) (1,0) (1,1) (1,2)]

Advertisement

Answer

The variable sum after the nested-for loops (as written in your code) is

JavaScript

You can work out the coordinates of the max sum by having a initial “pointer” at the bottom right corner (i=1, j =2, ignoring the zeros), and comparing the values that is on the top (i=0, i=2) and on the left (i=1, j=1). Since 8 is larger than 6, we move the “pointer” to the left, and now i=1, j=1.

4 is larger than 3, so we move the pointer to 4 (i=1, j=0)

1 is larger than 0, so we move the pointer to 1 (i=0, j=0)

A basic (untested) implementation of the algorithm is as follows:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement