数组查询
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)