We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Array Manipulation
Array Manipulation
Sort by
recency
|
2479 Discussions
|
Please Login in order to post a comment
bit ugly but it does the job in scala (60)
trick is to avoid inner loops for the queries and instead ADD value at the start index and SUBTRACT it at the end index + 1 (due to inclusive bounds)
also make sure to return long
Here's my approch
long arrayManipulation(int n, vector> queries) { vector arr(n,0); long a=0,max=0; long value,start,end;
for(int i=0; imax)max=arr[j]; } } return max; }
My Javascript solution:
The key point to understand from this solution is that the goal is to reduce the big O, and the way we do this is by avoiding the most logical way to approach this problem, which could be a nested loop. For example, we could loop through the queries array and then, inside it, loop n times to perform each operation in order to form the final array. But this would result in O(mn) time complexity.
Now, it's worth noticing that it doesn't really matter how many loops we go through, as long as they're not nested.
That's why in my solution, I don't iterate the queries array in order to form the final array, but instead, I go through it to form an array that allows me to form the final array by iterating it afterwards.
Let me give you an example. Let's say that I get this input: n **= 5 **a b k 2 4 2
Then, my resulting array after iterating the queries array would be: [0, 2, 0, 0, -2, 0] (remember that my array size is n+1 to store the last substraction, but is not relevant)
That doesn't tell us much at first glance, but if we iterate that array assigning the value of the summatory to each position, the result array would be: [0, 2, 2, 2, 0, 0]
Here's how: 0 0 + 2 = 2 2 + 0 = 2 2 + 0 = 2 2 + (-2) = 0 0 + 0 = 0 // this last element is just for calculation purposes
And... That's how we got the resultant array without nested loops!
Once I have the resultant array I just need to find the Max value of it.
As you can see I used 3 loops which results in O(a + b + c) but as you know, we dont care about less dominant terms so that can be reduced to O(n).
Hope this explanation helps to understand the solution.
My Java 8 Solution;
long arrayManipulation(int n, vector> queries) {
}