//分治算法
#include <stdio.h>
int MaxSubSum(int *a, int left, int right);
int MaxSum(int n, int *a);
int main()
{
int a[] = { -2, 11, -4, 13, -5, -2 };
for (int i = 0; i<6; i++)
{
printf("%d ", a[i]);
}
printf("\n");
printf("数组a的最大连续子段和为:%d\n", MaxSum(6, a));
return 0;
}
int MaxSubSum(int *a, int left, int right)
{
int sum = 0;
if (left == right)
{
sum = a[left]>0 ? a[left] : 0;
}
else
{
int center = (left + right) / 2;
int leftsum = MaxSubSum(a, left, center);
int rightsum = MaxSubSum(a, center + 1, right);
int s1 = 0;
int lefts = 0;
for (int i = center; i >= left; i--)
{
lefts += a[i];
if (lefts>s1)
{
s1 = lefts;
}
}
int s2 = 0;
int rights = 0;
for (int i = center + 1; i <= right; i++)
{
rights += a[i];
if (rights>s2)
{
s2 = rights;
}
}
sum = s1 + s2;
if (sum<leftsum)
{
sum = leftsum;
}
if (sum<rightsum)
{
sum = rightsum;
}
}
return sum;
}
int MaxSum(int n, int *a)
{
return MaxSubSum(a, 0, n - 1);
}
枫蜜柚子茶
- 粉丝: 8967
- 资源: 5351
最新资源
- vgg-generated-120.i
- CT7117体温传感器驱动代码
- 基于51单片机和HC-05蓝牙模块、Lcd模块、DS18B20温度传感器模块利用串口通信进行环境监测源码全部资料(高分项目)
- MID国家编码表 MMSI国家编码表 MMSI-MID 国家编码表 AIS 国家编码表
- 基于51单片机和HC-05蓝牙模块、Lcd模块、DS18B20温度传感器模块利用串口通信进行环境监测(完整高分项目代码)
- c05300 amoled datasheet
- ats3089 datasheet
- 矩芯 ats3085s datasheet
- 视频播放软件(Qt6项目)
- 《数据库系统原理》实验指导书-(信创云实验室).doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈