下面是O( n ^2 )和O(n^3)的暴力解法:
暴力解法就是使用嵌套循环的方式
将所有的连续序列组合的结果计算出来,然后相互比较。
#include <stdio.h>
extern int maxSubSum(int *num, int length);
void main()
{
int num[9] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int sum = maxSubSum(num, 9);
printf("%d\n", sum);
}
int maxSubSum(int *num, int length)
{
int maxsubsum = num[0];
for (int i = 0; i < length; i++)
{
for (int j = i; j < length; j++)
{
int thissum = 0;
for (int k = i; k <= j; k++)
{
thissum += num[k];
}
if (thissum > maxsubsum)
{
maxsubsum = thissum;
}
}
}
return maxsubsum;
}
可以对复杂度进行优化到O(n^2)
#include <stdio.h>
extern int maxSubSum(int *num, int length);
void main()
{
int num[9] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int sum = maxSubSum(num, 9);
printf("%d\n", sum);
}
int maxSubSum(int *num, int length)
{
int maxsubsum = num[0];
for (int i = 0; i < length; i++)
{
int thissum = 0;
for (int j = i; j < length; j++)
{
thissum += num[j];
if (thissum > maxsubsum)
{
maxsubsum = thissum;
}
}
}
return maxsubsum;
}