# Find maximum height pyramid from the given array of objects in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have an array of n objects. Each object has width W[i]. We have to arrange them in a pyramidal way like −

• Total width of ith is less than (i + 1)th

• Total number of objects in the ith is less than (i + 1)th

For example, if the weights are like [40, 100, 20, 30], then output will be 2. So top level is 30, then lower level 20, 40 and 100

To solve this, we will use the greedy approach. The idea is to use place the objects with lower width at the top, the next object at the level right below and so on. To get the maximum number of levels, sort the given array and try to form pyramid from top to bottom.

Then find the smallest element of array like the first element of array after sorting, place it on the top. Then try to build levels below it with greater number of objects and the greater width.

## Example

Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int maxLevelPyramid(int objects[], int n) {
sort(objects, objects + n);
int ans = 1;
int prev_w = objects[0];
int count_p = 1;
int count_c = 0;
int curr_w = 0;
for (int i=1; i<n; i++){
curr_w += objects[i];
count_c++;
if (curr_w > prev_w && count_c > count_p){
prev_w = curr_w;
count_p = count_c;
count_c = curr_w = 0;
ans++;
}
}
return ans;
}
int main() {
int boxes[] = {40, 100, 20, 30};
int n = sizeof(boxes)/sizeof(boxes[0]);
cout << "Max level of pyramid: " << maxLevelPyramid(boxes, n);
}

### Output

Max level of pyramid: 2
Updated on 03-Jan-2020 10:37:33