VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-path-right-number-triangle/

⇱ Maximum sum of a path in a Right Number Triangle - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of a path in a Right Number Triangle

Last Updated : 2 Feb, 2023

Given a right triangle of numbers, find the largest of the sum of numbers that appear on the paths starting from the top towards the base, so that on each path the next number is located directly below or below and one place to the right.

Examples : 

Input : 1
 1 2
 4 1 2
 2 3 1 1 
Output : 9
Explanation : 1 + 1 + 4 + 3

Input : 2
 4 1
 1 2 7
Output : 10
Explanation : 2 + 1 + 7

Recursion

The idea is to find the largest sum ending at every cell of the last row and return a maximum of these sums. We can recursively compute these sums by recursively considering the above two cells. 


Output
6

Complexity Analysis:

  • Time Complexity: O(2N*N) where N = number of rows and M = number of columns
  • Auxiliary Space: O(N)

Dynamic Programming - Top-Down Approach

Since there are overlapping subproblems, we use dynamic programming to find the maximum sum ending at a particular cell of the last row.
Below is the implementation of the above idea.


Output
6

Complexity Analysis:

  • Time Complexity: O(N*M) where N = number of rows and M = number of columns
  • Auxiliary Space: O(N2)

Dynamic Programming: Bottom-Up Approach

Since there are overlapping subproblems, we use dynamic programming to find the maximum sum ending at a particular cell of the last row. Below is the implementation of the above idea.


Output
6

Complexity Analysis:

  • Time Complexity: O(m*n) where m = no of rows and n = no of columns
  • Auxiliary Space: O(n2)

Space Optimization(Without changing the input matrix)

We don't need a matrix of m*n size. It will store all the results.
We just need the triangle row minimum of the immediate bottom row
So using this approach we can optimize the space from O(m*n) to O(n).
The approach remains the same as that of Method 3.


Output
6

Complexity Analysis:

  • Time Complexity: O(m*n) where m = no of rows and n = no of columns
  • Space Complexity: O(n)

Space Optimization (Changing the input matrix)


Output
6

Complexity Analysis:

  • Time Complexity: O(m*n) where m = no of rows and n = no of columns
  • Auxiliary Space: O(1)
Comment
Article Tags:
Article Tags: