0 like 0 dislike
1,018 views
| 1,018 views

0 like 0 dislike

Question 1
Given an array `A` of size `n`. Perform `q` queries on the array.
Query of type `x l r`. Add `x` to all elements in range of `l` to `r` inclusive.
Return the final sum of elements of array.

Constraints

`````` -10^3 <=x <=10^3
0<= l, r < N
1 <= q <= 10^5
1 <= N <= 10^5
``````

Example

``````A = [1,4,3,2,4]
queries = [[5,0,1],[-5,0,2]]

output = 9

Exaplaination: queries[0] => x=5, l=0, r=1   --> A = [6,9,3,2,4]
------------------------------------------------
queries[1] => x= -5, l=0, r=2    --> A = [1,4,-2,2,4]

sum(A) = 9 --> answer
``````
by Expert (46,090 points)
0 like 0 dislike

## Python O(n)

``````def findSumAfterQueries(nums,queries) :
res = sum(nums)
for x,l,r in queries:
res += (r-l+1)*x       ## x is added to all the elements in range l to r (total elements in range l to r = r-l+1)
return res

nums = [1,4,3,2,4]
queries = [[5,0,1],[-5,0,2]]
print(findSumAfterQueries(nums,queries))``````
by Expert (46,090 points)