3 回答

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
一種方法是將間隔分為開(kāi)始和結(jié)束,并根據(jù)您是否處于該間隔內(nèi)指定在總數(shù)中添加或減去多少。根據(jù)間隔在數(shù)軸上的位置對(duì)間隔進(jìn)行排序后,您可以遍歷它,根據(jù)您是否進(jìn)入或離開(kāi)間隔來(lái)添加或減去值。下面是一些執(zhí)行此操作的代碼:
def find_max_val(intervals):
operations = []
for i in intervals:
operations.append([i[0],i[2]])
operations.append([i[1]+1,-i[2]])
unique_ops = defaultdict(int)
for operation in operations:
unique_ops[operation[0]] += operation[1]
sorted_keys = sorted(unique_ops.keys())
print(unique_ops)
curr_val = unique_ops[sorted_keys[0]]
max_val = curr_val
for key in sorted_keys[1:]:
curr_val += unique_ops[key]
max_val = max(max_val, curr_val)
return max_val
intervals = [(1,2,100),(2,5,100),(3,4,100)]
print(find_max_val(intervals))
# Output: 200

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是 3 個(gè)間隔的代碼。
n = int(input())
x = [0]*n
interval = []
for i in range(3):
s = int(input()) #start
e = int(input()) #end
v = int(input()) #value
#add value
for i in range (s-1, e):
x[i] += v
print(max(x))

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用列表理解來(lái)完成很多工作。
n=5
intervals = [(1,2,100),(2,5,100),(3,4,100)]
intlst = [[r[2] if i>=r[0]-1 and i<=r[1]-1 else 0 for i in range(n)] for r in intervals]
lst = [0]*n #[0,0,0,0,0]
for ls in intlst:
lst = [lst[i]+ls[i] for i in range(n)]
print(lst)
print(max(lst))
輸出
[100, 200, 200, 200, 100]
200
添加回答
舉報(bào)