-
求一组数中连续的几个数之和最大值
给定一组数,有正有负,求连续的几个数之和的最大值?用程序设计实现。这是一道面试题目,鄙人只是总结了两种方法,如果朋友你有更好的方法来解决这个问题,希望你能回复,与大家分享一下。
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
/// 最笨的方法
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public int getMax(int[] a)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
//不能定义max为0
int max=a[0],temp=0;
![](/Images/OutliningIndicators/InBlock.gif)
if (a.Length == 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = 0;
return max;
}
if (a.Length == 1)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = a[0];//或者为0,如果一个元素也不取
return max;
}
for (int i = 0; i < a.Length; i++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for (int j = i; j < a.Length; j++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
temp = temp+a[j];
if (temp > max)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = temp;
}
}
temp = 0;
}
return max;
}
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
/// 第二种方法 将相邻的正数和零、负数整合成一个数,最后再比较
/// 这样做,最糟糕的就是怕集合的元素都是正负交替出现
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
public int SegetMax(int[] a)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
int max = a[0],temp=0, plusTemp = 0,negTemp=0;
![](/Images/OutliningIndicators/InBlock.gif)
int i=0,j=0;
List<int> list = new List<int>();
if (a.Length == 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = 0;
return max;
}
if (a.Length == 1)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = a[0];
return max;
}
while (i<a.Length)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (a[i] >= 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
while (j < a.Length&&a[j] >= 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
plusTemp = plusTemp + a[j];
j++;
}
i = j;
list.Add(plusTemp);
plusTemp = 0;
![](/Images/OutliningIndicators/InBlock.gif)
}
else if (a[i] < 0)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
while (a[j] < 0 && j < a.Length)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
negTemp = negTemp + a[j];
j++;
}
i = j;
list.Add(negTemp);
negTemp = 0;
}
}
for (int p = 0; p < list.Count; p++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for (int k = p; k < list.Count; k++)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
temp = temp + list[k];
if (temp > max)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
max = temp;
}
}
temp = 0;
}
return max;
}
第二种方法最后验证是错误的。int[] a ={ -1000000,-1,-3,-8728272,-8383828,-009993939 };
如果是这样,这种算法就存在问题,看来思路还是短路了。
-
相关阅读:
PSP ISO游戏运行必备工具:ISO TOOL 1.970 功能一览&图文教程
Linux防火墙(原书第3版) 电子书籍
iptables的相关概念和数据包的流程(图)
oracle数据库远程连接服务器配置tnsnames
编程感悟
工作任务三 打印表单数据
UltraWebTree的使用心得
DropDownList应用
使用UltraWebTree时,如何在刷新后展开之前选中的节点,并绑定相关数据
webgrid 添加行是不允许相同
-
原文地址:https://www.cnblogs.com/yank/p/1103189.html
Copyright © 2020-2023
润新知