0370 Range Addition

0370 Range Addition#

Problem#

Examples#

Example 1:


Constraint#


Analysis#

Solution#

def rangeAddition(length, updates):
    difference = [0 for i in range(length)]
    for update in updates:
        start, end, addition = update
        difference[start] += addition
        if end + 1 < length:
            difference[end+1] -= addition
    
    # reconstruct array
    res = [0 for i in range(length)]
    res[0] = difference[0]
    i = 1
    while i < length:
        res[i] = res[i-1] + difference[i]
        i += 1
    return res

length = 5
updates = [[1,3,2], [2,4,3], [0, 2, -2]]
print(rangeAddition(length, updates))
[-2, 0, 3, 5, 3]