zoukankan
html css js c++ java
求一组数中连续的几个数之和最大值
给定一组数,有正有负,求连续的几个数之和的最大值?用程序设计实现。这是一道面试题目,鄙人只是总结了两种方法,如果朋友你有更好的方法来解决这个问题,希望你能回复,与大家分享一下。
/**/
///
<summary>
///
最笨的方法
///
</summary>
///
<param name="a"></param>
///
<returns></returns>
public
int
getMax(
int
[] a)
{
//不能定义max为0
int
max
=a[
0]
,temp
=
0
;
if
(a.Length
==
0
)
{
max
=
0
;
return
max;
}
if
(a.Length
==
1
)
{
max
=
a[
0
];
//
或者为0,如果一个元素也不取
return
max;
}
for
(
int
i
=
0
; i
<
a.Length; i
++
)
{
for
(
int
j
=
i; j
<
a.Length; j
++
)
{
temp
=
temp
+
a[j];
if
(temp
>
max)
{
max
=
temp;
}
}
temp
=
0
;
}
return
max;
}
/**/
///
<summary>
///
第二种方法 将相邻的正数和零、负数整合成一个数,最后再比较
///
这样做,最糟糕的就是怕集合的元素都是正负交替出现
///
</summary>
///
<param name="a"></param>
///
<returns></returns>
public
int
SegetMax(
int
[] a)
{
int
max
=
a[
0]
,temp
=
0
, plusTemp
=
0
,negTemp
=
0
;
int
i
=
0
,j
=
0
;
List
<
int
>
list
=
new
List
<
int
>
();
if
(a.Length
==
0
)
{
max
=
0
;
return
max;
}
if
(a.Length
==
1
)
{
max
=
a[
0
];
return
max;
}
while
(i
<
a.Length)
{
if
(a[i]
>=
0
)
{
while
(j
<
a.Length
&&
a[j]
>=
0
)
{
plusTemp
=
plusTemp
+
a[j];
j
++
;
}
i
=
j;
list.Add(plusTemp);
plusTemp
=
0
;
}
else
if
(a[i]
<
0
)
{
while
(a[j]
<
0
&&
j
<
a.Length)
{
negTemp
=
negTemp
+
a[j];
j
++
;
}
i
=
j;
list.Add(negTemp);
negTemp
=
0
;
}
}
for
(
int
p
=
0
; p
<
list.Count; p
++
)
{
for
(
int
k
=
p; k
<
list.Count; k
++
)
{
temp
=
temp
+
list[k];
if
(temp
>
max)
{
max
=
temp;
}
}
temp
=
0
;
}
return
max;
}
第二种方法最后验证是错误的。
int[] a ={ -1000000,-1,-3,-8728272,-8383828,-009993939 };
如果是这样,这种算法就存在问题,看来思路还是短路了。
查看全文
相关阅读:
CSS3新特性
CSS简述
HTML5新属性
Python学习笔记(十二)
Python学习笔记(十一)
Python学习笔记(十)
Python学习笔记(九)
Python学习笔记(八)
Python学习笔记(七)
Python学习笔记(六)
原文地址:https://www.cnblogs.com/yank/p/1103189.html
最新文章
2019-2020-1学期 20202410《计算机科学概论》第五周学习总结
2019-2020-1学期 20202410《计算机科学概论》第四周学习总结
2019-2020-1学期 20202410《计算机科学概论》第三周学习总结
看我一行代码把图片变成字符画。
抓取虾米歌曲信息
twisted internet.reactor部分 源码分析
django 中的延迟加载技术,python中的lazy技术
一些web编程能用到的小知识
django 的请求处理部分----WSGIHandler 源码分析 django1.5.5
python 从SocketServer到 WSGIServer 源码分析、
热门文章
如何让玩家相信游戏是公平的?
987654321的阶乘转12进制末尾几个0? 的详细解决办法..
dota 路人水平鉴定器
html5新增API
移动端触屏事件
JS 本地存储
Web API
JavaScript基础
计算机基础知识
网页布局准则
Copyright © 2011-2022 走看看