最大サブアレイ合計O(n ^ 2)時間を見つけるC ++プログラム(単純な方法)
サブアレイの最大合計O(n ^ 2)時間を見つけるためのC ++プログラムを開発します(単純な方法)。
アルゴリズム
Begin Take the array elements as input. Make a loop for the length of the sub-array from 1 to n, within this loop, Make another loop nested with the previous one, calculate the sum of first sub-array of that length. For remaining sub-array sum, add the next element to the sum and subtract the first element of that sub-array. Compare it with the global max and update if found out to be more. Print the max sub-array and their sum as a result. End.
サンプルコード
#include<iostream>
using namespace std;
int main() {
int n, i, j, m=-1, s, ini_m, fi_m;
cout<<"\nEnter the number of data element in the array: ";
cin>>n;
int a[n];
for(i = 0; i < n; i++) {
cout<<"Enter element "<<i+1<<": ";
cin>>a[i];
}
for(i = 1; i < n+1; i++) {
s = 0;
for(j = 0; j < n; j++) {
if(j < i)
s += a[j];
else
s = s+a[j]-a[j-i];
if(m< s) {
ini_m = j-i+1;
fi_m = j;
m = s;
}
}
}
cout<<"\nThe maximum sub array is: ";
for(i = ini_m; i <= fi_m; i++)
cout<<a[i]<<" ";
cout<<"\nThe maximum sub-array sum is: "<<m;
} 出力
Enter the number of data element in the array: 10 Enter element 1: 1 Enter element 2: -2 Enter element 3: 3 Enter element 4: -4 Enter element 5: 5 Enter element 6: -6 Enter element 7: 7 Enter element 8: 8 Enter element 9: -9 Enter element 10: 10 The maximum sub array is: 7 8 -9 10 The maximum sub-array sum is: 16
-
C++で最も深いノードの合計を見つけるプログラム
二分木があるとしましょう。その最も深い葉の値の合計を見つける必要があります。したがって、ツリーが次のような場合- その場合、出力は11になります。 これを解決するには、次の手順に従います- マップmとmaxDepthを定義します 再帰メソッドsolve()を定義します。これはノードとレベルを取り、最初はレベルは0です ノードが存在しない場合は、戻ります maxDepth:=レベルの最大値とmaxDepth ノードの値だけm[レベル]を増やします 解決(ノードの左側、レベル+ 1) 解決(ノードの右側、レベル+ 1) mainメソッドで
-
Pythonでmを法とする部分配列の最大合計を見つけるプログラム
Pythonでmを法とする部分配列の最大合計を見つけるプログラム n個の要素を持つ配列numがあるとします。別の整数mがあります。 mを法とするサブ配列の合計の最大値を見つける必要があります。 したがって、入力がnums =[1,5,7,3] m =5のような場合、出力は3になります。 [1] mod 5 =1 [5] mod 5 =0 [7] mod 5 =2 [3] mod 5 =3 [1,5] mod 5 =1 [5,7] mod 5 =2 [7,3] mod 5 =0 [1,5,7] mod 5 =3 [5,7,3] mod 5 =0 [1,