Project Euler : Problem 18 - Maximum path sum I

3 minute read

Problem Statement : Maximum path sum I

Problem 18 : By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is .

That is, .

Find the maximum total from top to bottom of the triangle below:

NOTE: As there are only routes, it is possible to solve this problem by trying every route. However, , is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! :open_mouth:)

Concept and Theory

Lets take the first row and simulate how we get the defined path.

We can use two strategies. Start from the top most element and move downwards or we can start from the bottom row and go upwards.

Lets break it down and see if we can find some sub optimal solution.

Suppose there are only two rows, we can simply add to both the elements below and tell which path sum is greater.

Now lets consider another row and see if we can do the same thing as above and find out maximum sum path. But now we have two elements at the top, we can’t simply do as above. Hmmm What about we do same thing and pick which leads to the maximum sum. In the below diagram I have marked all those maximum elements which we can obtain in blue. I have also shown the other sum in green which we will be getting from other element. For eg. and will give us and and will give us for the same position. We will take as our answer since its the maximum among two possible path sums.

So after rows we have,

Lets consider last row,

Voila!!! we found our path with sum . But we have to check all the elements of the last row in the modified grid to find out the maximum or we can keep a variable which will be keeping track of largest sum found so far.

Another approach is to do same but starting from bottom row, and moving up. In this case the first element of first row will be the answer.

Code

/**
 * A function which returns the maximum path sum from top row to bottow row
 *
 * @param grid : the grid
 *
 * @return : maximum path sum
 */
public static int maximumPathSumI(int[][] grid) {

  for (int i = grid.length - 1; i > 0; i--) {
    for (int j = 0; j < grid[i].length - 1; j++) {
      grid[i - 1][j] += (Math.max(grid[i][j], grid[i][j + 1]));
    }
  }

  return grid[0][0];
}

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as given in the above mentioned post, , you just need to call it for each test case.

References and Further Readings

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...