Skip to content

Commit 2cacb28

Browse files
committed
Longest circus tower with decreasing height and decreasing weight
1 parent 3672e06 commit 2cacb28

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

17-Hard/8-Circus-Tower.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
Circus Tower:
3+
A circus is designing a tower routine consisting of people standing atop one another's
4+
shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than
5+
the person below him or her. Given the heights and weights of each person in the circus, write a
6+
method to compute the largest possible number of people in such a tower.
7+
8+
Solution:
9+
The problem is really the following:
10+
We have a list of pairs of items. Find the longest sequence such that both the first and second
11+
items are in non-decreasing order.
12+
13+
1. Sort the heights in decreasinn order.
14+
2. Now in the sorted array find the longest decreasing weight sub-array.
15+
*/
16+
17+
// g++ 8-Circus-Tower.cpp --std=c++11
18+
19+
#include <iostream>
20+
#include <vector>
21+
22+
using std::cout;
23+
using std::endl;
24+
using std::vector;
25+
26+
bool compHeight( const std::pair<int, int> a, const std::pair<int, int> b ) {
27+
return a.first > b.first;
28+
}
29+
30+
int longestIncreasingWeight( vector< std::pair<int, int> > htWtPairs ) {
31+
int globalLongest = 1;
32+
int longest = 1;
33+
for( int i = 1; i < htWtPairs.size(); i++ ) {
34+
if( htWtPairs[i].second < htWtPairs[i-1].second ) {
35+
longest += 1;
36+
if( longest > globalLongest ) {
37+
globalLongest = longest;
38+
}
39+
} else {
40+
longest = 1;
41+
}
42+
}
43+
return globalLongest;
44+
}
45+
46+
int getLongestHtAndWt( vector< std::pair<int, int> > htWtPairs ) {
47+
std::sort( htWtPairs.begin(), htWtPairs.end(), compHeight );
48+
return longestIncreasingWeight( htWtPairs );
49+
}
50+
51+
int main() {
52+
vector< std::pair<int, int> > heightAndWeight = { {65, 100}, {70, 150}, {56, 90}, {75, 190},
53+
{60,85}, {68,110} };
54+
cout<< getLongestHtAndWt( heightAndWeight ) << endl;
55+
vector< std::pair<int, int> > heightAndWeight1 = {{1,1}, {3,3}, {7,2}, {6,4}, {9,9}, {8,5}};
56+
cout<< getLongestHtAndWt( heightAndWeight1 ) << endl;
57+
return 0;
58+
}

0 commit comments

Comments
 (0)