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 };
如果是这样,这种算法就存在问题,看来思路还是短路了。
查看全文
相关阅读:
leetcode231 2的幂 leetcode342 4的幂 leetcode326 3的幂
leetcode300. Longest Increasing Subsequence 最长递增子序列 、674. Longest Continuous Increasing Subsequence
leetcode64. Minimum Path Sum
leetcode 20 括号匹配
算法题待做
leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown 、714. Best Time to Buy and Sell Stock with Transaction Fee
rand7生成rand10,rand1生成rand6,rand2生成rand5(包含了rand2生成rand3)
依图
leetcode 1.Two Sum 、167. Two Sum II
从分类,排序,top-k多个方面对推荐算法稳定性的评价
原文地址:https://www.cnblogs.com/yank/p/1103189.html
最新文章
deepin系统下如何设置wifi热点(亲测有效)
如何下载github项目中的部分文件(文件夹)
《将博客搬至CSDN》
python多线程学习笔记(超详细)
P4factory <Towards a better behavioral model: bmv2>
P4factory <Integration with Mininet>
P4factory 运行结果展示 basic_routing 以及 ./run_all_tests 的运行结果
【转载】wireshark:no interface can be used for capturing in this system with the current configuration
DS实验题 order
The P4 Language Specification v1.0.2 Parser
热门文章
【转载】哈希冲突
关于 “什么是互联网?” 的采访记录
简单排序算法 C++类实现
Ubuntu 安装搜狗拼音及fcitx
《高性能路由器 设计与实现》高性能路由器新型体系结构 小记
《高性能路由器 设计与实现》高性能路由器的组成 小记
BNF 巴科斯范式
The P4 Language Specification v1.0.2 Header and Fields
The P4 Language Specification v1.0.2 Introduction部分
面试题 最大子数组差
Copyright © 2011-2022 走看看