简体   繁体   中英

largest sum of any of the paths till row N-1

There is a N*N integer matrix Arr[N][N] . From the row r and column c, we can go to any of the following three indices:

I. Arr[ r+1 ][ c-1 ] (valid only if c-1>=0)

II. Arr[ r+1 ][ c ]

III. Arr[ r+1 ][ c+1 ] (valid only if c+1<=N-1)

So if we start at any column index on row 0, what is the largest sum of any of the paths till row N-1.

You can solve this problem like this:

Let M be the largest number in the NxN integer matrix A. Define a new N*N matrix B where b[i,j] = M - a[i,j] + 1 . B contains only positive integers. The traversal method corresponds to a certain well-defined directional graph on the cells of the matrix. Now use the dijkstra algorithm on this graph, where the distances of each node to the three (or two in the cases on the edges) nodes above is simply equal to the number b[i,j] . The dijkstra algorithm will give you the 'shortest' path in this graph, which corresponds to the path with the largest sum in the matrix A.

To see why the problem can be solved in this way, suppose there are x sequences s1, s2, s3, ..., sx of equal length N. Some sequence si will have the largest sum. If we take sequences t1, t2, ..., tx so that t1k = -s1k, then the largest sum s is the smallest sum t. If we then add a constant to each of the values in each sequence then the t sequence with the largest sum does not change, for each of these sequences is equally long.

This problem can be solved using Dynamic Programming or using recursion. Here is a solution written in Java using Dynamic Programming approach:
http://design-interviews.blogspot.com/2014/11/largest-sum-of-any-of-paths-till-row-n.html

The time complexity of the solution is O(n^2). This solution changes the original input matrix. If it is needed to keep the original matrix intact, then another two-dimensional array needs to be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM