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 length of a sub-array with ugly numbers in C++
Problem statement
Given an array arr[] of N elements (0 ≤ arr[i] ≤ 1000). The task is to find the maximum length of the sub-array that contains only ugly numbers.
Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
For Example below are the few number from series: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,…
Example
If input array is {1, 2, 7, 9, 120, 810, 374} then answer is 3 as −
Longest possible sub-array of ugly number sis {9, 120, 810}
Algorithm
- Take a unordered_set, and insert all the ugly numbers which are less than 1000 in the set
- Traverse the array with two variables named current_max and max_so_far.
- Check for each element if it is present in the set
- If an ugly number is found, then increment current_max and compare it with max_so_far
- If current_max > max_so_far then max_so_far = current_max.
- Every time a non-ugly element is found, reset current_max = 0.
Example
#include <bits/stdc++.h>
using namespace std;
unsigned getUglyNumbers(int n) {
int ugly[n];
int i2 = 0, i3 = 0, i5 = 0;
int next_multiple_of_2 = 2;
int next_multiple_of_3 = 3;
int next_multiple_of_5 = 5;
int next_ugly_no = 1;
ugly[0] = 1;
for (int i = 1; i < n; i++) {
next_ugly_no = min(next_multiple_of_2, min(next_multiple_of_3, next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2) {
i2 = i2 + 1;
next_multiple_of_2 = ugly[i2] * 2;
}
if (next_ugly_no == next_multiple_of_3) {
i3 = i3 + 1;
next_multiple_of_3 = ugly[i3] * 3;
}
if (next_ugly_no == next_multiple_of_5) {
i5 = i5 + 1;
next_multiple_of_5 = ugly[i5] * 5;
}
}
return next_ugly_no;
}
int maxUglySubarray(int arr[], int n) {
unordered_set<int> s;
int i = 1;
while (1) {
int next_ugly_number = getUglyNumbers(i);
if (next_ugly_number > 1000)
break;
s.insert(next_ugly_number);
i++;
}
int current_max = 0, max_so_far = 0;
for (int i = 0; i < n; i++) {
if (s.find(arr[i]) == s.end())
current_max = 0;
else {
current_max++;
max_so_far = max(current_max,
max_so_far);
}
}
return max_so_far;
}
int main() {
int arr[] = {1, 2, 7, 9, 120, 810, 374};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum sub-array size of consecutive ugly numbers = " << maxUglySubarray(arr, n) << endl;
return 0;
}
Output
When you compile and execute above program. It generates following output −
Maximum sub-array size of consecutive ugly numbers = 3
Advertisements