# Maximum height of triangular arrangement of array values in C++

C++Server Side ProgrammingProgramming

## Problem statement

Given an array, we need to find the maximum height of the triangle which we can form, from the array values such that every (i+1)th level contain more elements with the larger sum from the previous level.

## Example

If input array is {40, 100, 20, 30 } then answer is 2 as −

We can have 100 and 20 at the bottom level and either 40 or 30 at the upper level of the pyramid

## Algorithm

Our solution just lies on the logic that if we have maximum height h possible for our pyramid then ( h * (h + 1) ) / 2 elements must be present in the array

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaximumHeight(int *arr, int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
long long y = (i * (i + 1)) / 2;
if (y < n) {
result = i;
} else {
break;
}
}
return result;
}
int main() {
int arr[] = {40, 100, 20, 30};
int n = sizeof(arr) / sizeof(arr);
cout << "Result = " << getMaximumHeight(arr, n) << endl;
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Result = 2