# Program to find minimum number of pins required to hang all banners in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of intervals of the form [start, end] this is representing the starts and end points of banners we want to hang. At least one pin is required to hang a banner, and one pin can hang more than once banners. We have to find the smallest number of pins required to hang all the banners.

So, if the input is like intervals = [[2, 5],[5, 6],[8, 10],[10, 13]], then the output will be 2, as we can put two pins at position 5 and 10 to hang all of the banners.

To solve this, we will follow these steps −

• sort the array v based on the end values of intervals
• ret := 0
• last := -inf
• for each item it in v −
• if last >= start of it, then −
• (increase ret by 1)
• last := end of it
• return ret

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
static bool cmp(vector<int>& a, vector<int>& b) {
return a.back() < b.back();
}
int solve(vector<vector<int>>& v) {
sort(v.begin(), v.end(), cmp);
int ret = 0;
int last = -1e8;
for (auto& it : v) {
if (last >= it) {
continue;
}
ret++;
last = it;
}
return ret;
}
};
int solve(vector<vector<int>>& intervals) {
return (new Solution())->solve(intervals);
}
int main(){
vector<vector<int>> v = {{2, 5},{5, 6},{8, 10},{10, 13}};
cout << solve(v);
}

## Input

{{2, 5},{5, 6},{8, 10},{10, 13}}

## Output

2