实施Kadane算法的C ++程序
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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短