-6

You are given a list of size N, initialized with zeroes. You have to perform M operations on the list and output the maximum of final values of all the N elements in the list. For every operation, you are given three integers a,b and k and you have to add value to all the elements ranging from index to (both inclusive).

Input Format

First line will contain two integers N and M separated by a single space. Next M lines will contain three integers a,b and k separated by a single space. Numbers in list are numbered from 1 to N .

Constraints
Click here

Output Format

A single line containing maximum value in the updated list.

Sample Input

5 3
1 2 100
2 5 100
3 4 100

Sample Output

200

Explanation
After first update list will be 100 100 0 0 0.
After second update list will be 100 200 100 100 100.
After third update list will be 100 200 200 200 100.
So the required answer will be 200.

One of the Solutions with less time complexity

n, inputs = [int(n) for n in input().split(" ")]
list = [0]*(n+1)
for _ in range(inputs):
    x, y, incr = [int(n) for n in input().split(" ")]
    list[x-1] += incr
    if((y)<=len(list)): 
        list[y] -= incr
max = x = 0
for i in list:
    x=x+i;
    if(max<x):max=x
print(max)

Can someone explain the above solution?

1 Answers1

1

Basically it stores deltas rather than the final list; that means each operation only takes 2 reads and writes rather than (b - a + 1). Then the final max scan adds the deltas as it goes along, which is still an O(n) operation which you would have had to do anyway.

n, inputs = [int(n) for n in input().split(" ")]

Get the list size (n) and number of operations (m), ie 5 and 3

list = [0]*(n+1)

Create an empty 0-filled list. Should be lst = [0] * n (do not use list as a variable name, it shadows the built-in type) (we do not need an extra end cell, except as a checksum on our algorithm - if it works properly the final checksum should be 0).

for _ in range(inputs):
    x, y, incr = [int(n) for n in input().split(" ")]

Get an operation (a, b, k) ie 1, 2, 100.

    list[x-1] += incr

Add delta to the starting cell

    if((y)<=len(list)): 
        list[y] -= incr

Subtract the delta from the ending cell (should be if y < n: lst[y] -= incr)

The algorithm may be easier to understand if you add a print(lst) here (after the if but inside the for loop).

Now process the deltas to find the maximum item:

max = x = 0
for i in list:
    x=x+i;

x is now the value the actual value of the current list cell. Also max is a terrible variable name because it shadows the built-in max() function.

    if(max<x):max=x

Keep a running max tally

print(max)

Show the result.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99