数组查询

数组查询
Description
Given an array, the task is to complete the function which finds the maximum sum subarray, where you may remove at most one element to get the maximum sum.

Input
第一行为测试用例个数T;后面每两行表示一个用例,第一行为用例中数组长度N,第二行为数组具体内容。

Output
每一行表示对应用例的结果。

Sample Input 1
1
5
1 2 3 -4 5

Sample Output 1
11
Hint

例如,对一个数组A[] = {1, 2, 3, -4, 5},要移除-4得到最大和的子数组,和为11.

def solution(l):
    if min(l) >= 0 :
        return sum(l)
    # 肯定有负数,所以提前遍历去除一个数,然后使用一维动态规划
    else:
        # 返回结果
        res = min(l)
        for i in l:
            copy_l = l.copy()
            copy_l.remove(i)
            temp = 0
            for j in copy_l:
                temp += j
                res = max(res, temp)
                if temp < 0:
                    temp = 0
        return res


if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        number = int(input())
        l = list(map(int, input().strip().split()))
        result = solution(l)
        print(result)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值