# Minimum number of sets with numbers less than Y in C++

## Problem statement

Given a string of consecutive digits and a number Y, the task is to find the number of minimum sets such that every set follows the below rule −

• Set should contain consecutive numbers
• No digit can be used more than once.
• The number in the set should not be more than Y.

## Example

If str = “1234” and Y = 20 then answer is 3 as below sets are created −

{12} {3} and {4}

## Algorithm

• Convert string to number
• If the number is not greater than Y, then mark f = 1
• If the number exceeds Y, then increase count if f = 1 and re-initialize f as 0 and also initialise num as s[i]-‘0’ or num as 0
• After iterating in the string completely, then increase count if f is 1

## Example

#include <iostream>
#include <string>
using namespace std;
int getMinSets(string str, int y) {
int cnt = 0;
int num = 0;
int l = str.length();
int f = 0;
for (int i = 0; i < l; ++i) {
num = num * 10 + str[i] - 48;
if (num <= y) {
f = 1;
continue;
}
if (f) {
++cnt;
}
num = str[i] - '0';
f = 0;
if (num <= y) {
f = 1;
} else {
num = 0;
}
}
if (f) {
++cnt;
}
return cnt;
}
int main() {
string str = "1234";
int y = 20;
cout << "Minimum sets = " << getMinSets(str, y) << endl;
return 0;
}

## Output

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

Minimum sets = 3

Advertisements