C ++程序查找最大子数组总和O(n ^ 2)时间(天真的方法)
我们将开发一个C++程序来找到最大子数组和O(n^2)的时间(天真方法)。
算法
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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短