Kadane의 알고리즘은 정수 배열에서 최대 하위 배열 합계를 찾는 데 사용됩니다. 여기에서 우리는 이 알고리즘을 구현하기 위한 C++ 프로그램에 대해 논의할 것입니다.
알고리즘
Begin Function kadanes(int array[], int length): Initialize highestMax = 0 currentElementMax = 0 for i = 0 to length-1 currentElementMax = max(array[i],currentElementMax + array[i]) highestMax = max(highestMax, currentElementMax) return highestMax End
예시
#include<iostream>
using namespace std;
int kadanes(int array[],int length) {
int highestMax = 0;
int currentElementMax = 0;
for(int i = 0; i < length; i++){
currentElementMax =max(array[i],currentElementMax + array[i]) ;
highestMax = max(highestMax,currentElementMax);
}
return highestMax;
}
int main() {
cout << "Enter the array length: ";
int l;
cin >> l;
int arr[l];
cout << "Enter the elements of array: ";
for (int i = 0; i < l; i++) {
cin >> arr[i];
}
cout << "The Maximum Sum is: "<<kadanes(arr,l) << endl;
return 0;
} 출력
Enter the array length: 7 Enter the elements of array: -1 -2 -3 -4 -5 6 7 The Maximum Sum is: 13