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]

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: