Your code is ok for the chosen approach (passing the vector by value to the function aside). Your approach is inefficient. You need to choose a different algorithm.
The example input is n= 10
and queries = [[1,5,3],[4,8,7],[6,9,1]]
.
Look at the whole range:
0 1 2 3 4 5 6 7 8 9 index
1 1 1 1 1 1 1 1 1 1 original array
3 3 3 3 3 1st query
7 7 7 7 7 2nd query
3 3 3 3 3rd query
1 4 4 4 11 11 11 11 11 3 sum
What your algorithm does is applying all the steps in order of this table, then iterates the array to get the maximum.
Instead of that you can merge the intervals:
Start with
[1,5,3]
Add [4,8,7]
-> [1,3,3] , [4,5,10] , [6,8,3]
Add [6,9,1]
-> [1,3,3] , [4,5,10] , [6,8,4] , [9,9,1]
Because I didnt include the initial ones, ie [0,n-1,1]
, the result is 10+1 = 11
.
This is what the challenge is about, to find a way to retrive the result without actually carrying all the steps. When it says: You are given an array, and perform operations on that array, then determine the max element of the array, then you do not actually need the array. You only need to compute the maximum element in a hypothetical array with elements as if you carried out the operations.
I didn't think it trough completely, but I would expect the above to have much better complexity than your brute force approach. It does not depend on the number of elements in the array, only on the number of queries.
Do the maths first. Now you can start writing the code.
PS: There is a mistake in adding the invervals above. I hope you get the idea nevertheless.