通过对重叠区间求和找到最大元素

Find the maximum element by summing overlapping intervals

假设我们得到了区间的总大小space。假设我们还得到了一个元组数组,给了我们要求和的区间的开始和结束索引以及一个值。完成所有求和后,我们要 return 最大元素。我将如何有效地解决这个问题?

输入格式:n = 区间 space,区间 = 包含开始索引、结束索引和要添加到每个元素的值的元组数组


    Eg: 
    Input: n = 5, intervals = [(1,2,100),(2,5,100),(3,4,100)]
    Output: 200
    
    so array is initially [0,0,0,0,0]
    
    At each iteration the following modifications will be made:
    1) [100,100,0,0,0]
    2) [100,200,100,100,100]
    3) [100,200,200,200,100]
    
    Thus the answer is 200.

到目前为止我想出的就是拼接数组并向拼接部分添加值的暴力解决方案。我怎样才能做得更好?感谢您的帮助!

一种方法是将间隔分为开始和结束,并根据您是否在该间隔内指定向总数添加或减去多少。根据间隔在数字线上的位置对间隔进行排序后,您可以遍历它,根据您是进入还是离开间隔来添加或减去值。这是一些代码:

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   

                                                                 

这是 3 个间隔的代码。

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))

您可以使用列表理解来完成很多工作。

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