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 };
如果是这样,这种算法就存在问题,看来思路还是短路了。
查看全文
相关阅读:
Storm入门(二)集群环境安装
JAVA字符集
JAVA中int、String的类型转换
JAVA中int、String的类型转换
使用字节流读写中文字符
10个实用的但偏执的Java编程技术
10个实用的但偏执的Java编程技术
解析java实体类
解析java实体类
SSh三大框架的作用
原文地址:https://www.cnblogs.com/yank/p/1103189.html
最新文章
最小密度路径
洛谷P3966 [TJOI2013]单词(后缀自动机)
CF17E Palisection(回文自动机)
回文自动机学习笔记
洛谷P4762 [CERC2014]Virus synthesis(回文自动机+dp)
洛谷P4287 [SHOI2011]双倍回文(回文自动机)
洛谷P3649 [APIO2014]回文串(回文自动机)
Manacher算法学习笔记
洛谷P3527 [POI2011]MET-Meteors(整体二分)
bzoj1412: [ZJOI2009]狼和羊的故事(最小割)
热门文章
洛谷P3006 [USACO11JAN]瓶颈Bottleneck(堆模拟)
Storm入门(十一)Twitter Storm源代码分析之CoordinatedBolt
Storm入门(十)Twitter Storm: Transactional Topolgoy简介
Storm入门(九)Storm常见模式之流聚合
Storm入门(八)Storm实战常见问题总结(持续更新)
Storm入门(七)可靠性机制代码示例
Storm入门(六)深入理解可靠性机制
Storm入门(五)Twitter Storm如何保证消息不丢失
Storm入门(四)WordCount示例
storm入门(三)HelloWorld示例
Copyright © 2011-2022 走看看