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 };
如果是这样,这种算法就存在问题,看来思路还是短路了。
查看全文
相关阅读:
环境变量
多重继承
参数检查(@property)
限制属性绑定(__slots__)
实例属性和类属性
2017-11-28 中文编程语言之Z语言初尝试: ZLOGO 4
2017-10-23 在各种编程语言中使用中文命名
2017-11-27 汉化了十数个编译器的前辈的心得体会
五行
阴阳
原文地址:https://www.cnblogs.com/yank/p/1103189.html
最新文章
设计模式资源总结---模式无处不在
Java网上学习资料
C程序的内存分配
Java RMI学习
分布式系统&并发编程论文阅读计划
互联网文化
JavaWeb开发回顾总结【不断更新中】
算法: 包含min函数的栈
算法:顺时针打印矩阵
算法:二叉树镜像
热门文章
算法:数的子结构
算法:反转链表。
算法:合并两个排序的链表
Servlet工作原理解析 《深入分析java web 技术内幕》第九章
算法:调整数组顺序,使奇数位于偶数前面;
算法:输入一个链表,输出该链表中倒数第k个结点。
关于bug的一些思考
可迭代对象(__iter__()和__next__())
打印对象(__str__()和__repr__())
实例调用(__call__())
Copyright © 2011-2022 走看看