求最大连续子数组和(最大子段和)
一、题目简介
给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
引用自《百度百科》
二、编写代码
coding地址
def maxnum(number):
if len(number)==0:
return 0
num=number.copy()
max=0
for i in range(1,len(number)):
if num[i-1]>0:
num[i]=num[i-1]+number[i]
else:
num[i]=number[i]
if num[i]>max:
max=num[i]
return max
三、程序流程图
四、单元测试
1、测试代码
import unittest
from MAX import *
number1=[]
number2=[-2,11,-4,13,-5,-2]
number3=[-1,-2,-3,-4,-5]
number4=[-5,19,-9,4,-5]
class TestMathFunc(unittest.TestCase):
def test_maxnum1(self):
self.assertEqual(0, maxnum(number1),"Wrong!")
def test_maxnum2(self):
self.assertEqual(20, maxnum(number2),"Wrong!")
def test_maxnum3(self):
self.assertEqual(0, maxnum(number3),"Wrong!")
def test_maxnum4(self):
self.assertEqual(19, maxnum(number4),"Wrong!")
if __name__ == '__main__':
unittest.main()
2、判定/条件覆盖测试
满足一下覆盖条件
len(number)==0
len(number)!=0
num[i]>0
num[i]<=0
num[i]>sum
num[i]<=sum
3、测试结果