
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Height of Triangular Arrangement of Array Values in C++
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
#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[0]); cout << "Result = " << getMaximumHeight(arr, n) << endl; return 0; }
Output
When you compile and execute above program. It generates following output −
Result = 2
Advertisements