求子数组的最大和
2010-11-29 21:29
155 查看
题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
C语言代码:
#include <stdio.h>
#include <time.h>
int a[11] = {-3,0,6,2,-1,-4,3,2,6,-90,6};
int main()
{
int maxd = 0;
int maxever = 0;
int count = 0;
int start = 0;
int thisstart =0;
int end = 0;
for(count = 0;count<11;count++)
{
maxd += a[count];
if(maxd < 0)
{
maxd = 0;
thisstart = count+1;
}
if(maxd > maxever)
{
start = thisstart;
maxever = maxd;
end = count;
}
}
printf("start = %d/t end = %d/t 最大子数组和 = %d/n",start,end,maxever);
getchar();
}
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
C语言代码:
#include <stdio.h>
#include <time.h>
int a[11] = {-3,0,6,2,-1,-4,3,2,6,-90,6};
int main()
{
int maxd = 0;
int maxever = 0;
int count = 0;
int start = 0;
int thisstart =0;
int end = 0;
for(count = 0;count<11;count++)
{
maxd += a[count];
if(maxd < 0)
{
maxd = 0;
thisstart = count+1;
}
if(maxd > maxever)
{
start = thisstart;
maxever = maxd;
end = count;
}
}
printf("start = %d/t end = %d/t 最大子数组和 = %d/n",start,end,maxever);
getchar();
}
相关文章推荐
- 求子数组的最大和
- 求子数组的最大和
- 求子数组的最大乘积
- 编程之美--求子数组之和的最大值
- 求子数组的最大和
- 求子数组的最大和(数组)
- 面试100题:3.求子数组的最大和
- 求子数组的最大和
- 微软等数据结构+算法面试100题(44)-- 求子数组的最大和
- 求子数组的最大和
- 求子数组的最大和问题--一道浙江大学考研压轴题(被Google拿来做面试题)
- 课堂测试-求子数组和最大值
- 3.求子数组的最大和
- 求子数组的最大和
- Java实现算法之--求子数组和的最大值
- [JAVA算法]求子数组的最大和
- 微软面试100题之第三题:求子数组的最大和
- 面试题五:求子数组的最大和
- 求子数组的最大和
- 【编程题目】求子数组的最大和 ☆