Programming Challenge: Given a triangle of numbers, find the path from the top to the bottom of the triangle with the largest sum.

Emerald_Knight
Sat, 23 Jun 2018 05:29:26 +0000

This problem is based on the Project Euler problem here.

Goal: Given some input describing a triangle of numbers, find the path starting from the top-most row of the triangle and ending at the bottom-most row of the triangle that contains the largest sum of all of the numbers along the path. You may only move downward and you must select an adjacent position to move to. Efficiency is not a requirement for completion.

Constraints:

The first line of input for a triangle will be a single integer telling you how many rows the triangle will have.

Each following line of input will be the next row of the number triangle, starting at the first row.

For each line describing the number triangle, the individual numbers will be separated by a single space.

Note: The constraints above are to keep hard-coded triangles out of submitted solutions while also ensuring that all languages can equally handle this problem without annoying workarounds for lower-level languages. The consistency also makes it easier for beginners to review and understand someone else's code, and makes it easier to receive help if you get stuck. They're not necessarily required, but are highly encouraged.

Example input:

4
1
3 2
4 5 6
7 8 9 10

Corresponding triangle:

   1
  3 2
 4 5 6
7 8 9 10

Expected result: 19 (1 + 2 + 6 + 10)

Extra Credit: As noted on the Project Euler page, you can solve this using a brute force method, but it's incredibly inefficient. Specifically, a brute force solution would be O(2n) time (exponential). There exists a solution that can be solved in O(n²) time (quadratic). Find this solution.

Comments URL: https://tildes.net/~comp/2ob/programming_challenge_given_a_triangle_of_numbers_find_the_path_from_the_top_to_the_bottom_of_the

Votes: 13

Comments: 11