Click here to Skip to main content
14,971,029 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
A number pyramid is a set of (y=number of layers) layers of numbers that are stacked on top of each other. The (x=amount) th layer has(x=amount) numbers. A branch of the pyramid is a sequence of numbers starting from the topmost number, with each successive number being one to either the right or left of the current number, in the layer below it.    

For example consider this pyramid.

                                2
                            5       6                               
                        1       2       5
                    10      5       9       3

Starting from 2 at the top, move to 6 in the second layer. From 6 you can move to 2 or 5 below it, but not to 1. Continuing like this, we get a branch.  

You have to start from the top and go down in a selected branch and calculate the sum of the numbers in the branch on your way down. What would be the maximum sum you can collect in any such branch?

What I have tried:

Python
# Function to demonstrate printing pattern
def sumarray(n):
    n=input(int)
    global sumarray
     
    # outer loop to handle number of rows
    # n in this case
    for i in range(0, sumarray):
     
        # inner loop to handle number of columns
        # values changing acc. to outer loop
        for j in range(0, i+1,):
         
            
            n=(end=="")
            a=("",n)
            a=("\r")
      
        # ending line after each row
        calculate=sum(end(split().sprit()))
        print(calculate)
 
# Driver Code
Posted
Updated 2-Jun-21 8:16am
v2

1 solution

Use a recursive function to process the left and right sides: return the largest.

Think about it:
If you look at one of the smallest branches:
   1
10   5
You have two totals: 11, and 6.
You can the treat that result as a node for the node above.

No explicit loop is needed, the recursion handles that.

Try it on paper: you'll see what I mean.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900