题目:给定一个包含n个负数和正数的数组,要构建一个新数组,顺序为负数和偶数相间,例如:
[1,-2,1,-3,1]或[-1,2,-3],要求有最大和的子数组
思路:就是要在每次符号变换的时候找到变换前的所有数里面找到最大的值
两种做法:
暴力法:
for _ in range(int(input())):
n = int(input())
a =[*map(int, input().split())]
ans=0
i = 0
while i < n:
if a[i] < 0:
tmp = a[i]
while i < n and a[i] < 0:
tmp = max(tmp, a[i])
i += 1
else:
tmp = a[i]
while i < n and a[i] > 0:
tmp = max(tmp,a[i])
i += 1
ans += tmp
print(ans)
暴力法改良:
for _ in range(int(input())):
n = int(input())
a =[*map(int, input().split())]
ans, tmp = 0, a[0]
for i in a:
if tmp * i < 0:
ans += tmp
tmp = i
tmp = max(tmp, i)
ans += tmp
print(ans)
库函数法:
from itertools import groupby
for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
v = groupby(a, lambda x:x < 0)
print(sum([max(i[1]) for i in v]))