最大の合計連続サブアレイ
動的計画法を使用して、現在の項までの最大合計を保存します。配列内の連続する要素の合計を見つけるのに役立ちます。
入力と出力
Input:
An array of integers. {-2, -3, 4, -1, -2, 1, 5, -3}
Output:
Maximum Sum of the Subarray is: 7 アルゴリズム
maxSum(array, n)
入力- メインアレイ、アレイのサイズ。
出力- 最大合計。
Begin tempMax := array[0] currentMax = tempMax for i := 1 to n-1, do currentMax = maximum of (array[i] and currentMax+array[i]) tempMax = maximum of (currentMax and tempMax) done return tempMax End
例
#include<iostream>
using namespace std;
int maxSum( int arr[], int n) {
int tempMax = arr[0];
int currentMax = tempMax;
for (int i = 1; i < n; i++ ) { //find the max value
currentMax = max(arr[i], currentMax+arr[i]);
tempMax = max(tempMax, currentMax);
}
return tempMax;
}
int main() {
int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = 8;
cout << "Maximum Sum of the Sub-array is: "<< maxSum( arr, n );
} 出力
Maximum Sum of the Sub-array is: 7
-
C++のツリーで最大のサブツリーの合計を検索します
この問題では、二分木が与えられます。私たちのタスクは、ツリー内で最大のサブツリーの合計を見つけることです。 問題の説明: 二分木は、正の値と負の値で構成されます。そして、ノードの合計が最大のサブツリーを見つける必要があります。 問題を理解するために例を見てみましょう。 出力: 13 説明: 左サブツリーの合計は7です 右サブツリーの合計は1です ツリーの合計は13です ソリューションアプローチ この問題を解決するために、ポストオーダートラバーサルを実行します。ノードの左側のサブツリーと右側のサブツリーの合計を計算します。現在のノードについて、現在のノードの
-
Pythonでの連続した数字の最大の製品
=k桁であることが保証されていることに注意する必要があります。 したがって、入力がnum=52689762およびk=4の場合、出力は3024になり、4つの連続する桁の最大積は(8 * 9 * 7 * 6)=3024になります。 これを解決するには、次の手順に従います- 最大:=0 cand:=1 0、do 桁:=(数字の最後の桁)^ k cand:=1 0の場合、実行 cand:=cand *(digits mod 10) candが0と同じ場合、 ループから抜け出す 桁数:=桁数/ 10 最大:=最大および率直な最大値 num:=nums/10の商