Construct a Special Triangle from a Given Array

Objective: Given an array of integers such that first level will print all the elements in the array and from then at each level number of elements will be one less than the previous level and elements at the level will be the Sum of consecutive elements in the previous level. Print it in a reverse level. See Example.

Example:

Construct-a-Special-Triangle-from-a-Given-Array

Construct-a-Special-Triangle-from-a-Given-Array

Approach:

  • Recursion is the key.
  • At each iteration create a new array which contains the Sum of consecutive elements in the array passes as parameter.
  • Make a recursive call and pass the newly created array in the previous step.
  • While back tracking print the array (for printing in reverse order)

Code:


Output:

[48]
[20, 28]
[8, 12, 16]
[3, 5, 7, 9]
[1, 2, 3, 4, 5]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: