【例1】
给出一个长度为n的数组a1、a2、…、an,请找出在所有连续区间中,区间和最大同时这个区间0的个数小于等于3个,输出这个区间和。
输入:第一行一个正整数n,表示数组长度,1 <= n <= 1000000。
第二行为n个正整数a1 a2 … an,其中-1e9 <= a1,a2,…,an <= 1e9
输出:一个整数
样例:
输入1: 5
1 2 3 4 5
输出1: 15
输入2: 6
15 0 0 0 0 20
输出2: 20
Python实现
n = int(input())
nums = []
for i in range(0,n):
nums.append(int(input()))
total = [0,0,0]
zero_pos = [-1,-1,-1]
zero_seq = 0
max_ = 0
for i in range(0,n):
if 0 == nums[i]:
if zero_seq < 2:
zero_seq += 1
else:
if sum(total) > max_:
max_ = sum(total)
temp = total[1:3]
temp.append(0)
total = temp
else:
total[zero_seq] += nums[i]
if sum(total) > max_:
max_ = sum(total)
print(max_)
<