C++での醜い数字のサブ配列の最大長
問題の説明
N個の要素の配列arr[]が与えられます(0≤arr[i]≤1000)。タスクは、醜い数字のみを含むサブ配列の最大長を見つけることです。
醜い数は、素因数が2、3、または5だけの数です。
以下の例は、シリーズのいくつかの数字です:1、2、3、4、5、6、8、9、10、12、15、…
例
入力配列が{1、2、7、9、120、810、374}の場合、答えは3 as-
醜い数の可能な最長のサブ配列sis{9、120、810}
アルゴリズム
- unordered_setを取得し、1000未満の醜い数字をすべてセットに挿入します
- current_maxとmax_so_farという名前の2つの変数を使用して配列をトラバースします。
- 各要素がセットに存在するかどうかを確認します
- 醜い数字が見つかった場合は、current_maxをインクリメントし、max_so_farと比較します
- current_max> max_so_farの場合、max_so_far=current_max。
- 醜くない要素が見つかるたびに、current_max=0をリセットします。
例
#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;
} 出力
上記のプログラムをコンパイルして実行する場合。次の出力を生成します-
Maximum sub-array size of consecutive ugly numbers = 3
-
C++の積に等しいLCMの最大長サブアレイ
配列Aがあるとします。サブ配列の最大長を見つける必要があります。そのLCMは、そのサブ配列の要素の積と同じです。そのようなサブ配列が見つからない場合は、-1を返します。配列が{6、10、21}で、長さが2であるとすると、サブ配列{10、21}があり、そのLCMは210で、積も210です。 アプローチは簡単です。 2以上の長さの可能なすべてのサブ配列をチェックする必要があります。サブ配列が条件を満たす場合は、回答を最大の回答とサブ配列の長さとして更新します。 例 #include <iostream> using namespace std; int gcd(int a, int
-
C++でのペアの最大長チェーン
ペアのチェーンが与えられています。各ペアには2つの整数があり、最初の整数は常に小さく、2番目の整数は大きいので、同じルールをチェーンの構築にも適用できます。ペア(x、y)は、q