1343C Alternating Subsequence

在这里插入图片描述
题目:给定一个包含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]))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值