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.
Hi. As for why we subtract k, I just added a detailed example to help answer your question in my original post.
Regarding the exact values of a and b, it's a little tricky since a and b are 1-indexed but our array is 0-indexed. So we want to subtract 1 from both a and b. However, for b we re-add 1 because we want to change values from a to binclusive as stated in the problem, so we want the end of the interval to be 1 to the right of b which is why we re-add the 1.
long int arr[n+1];
memset(arr,0,sizeof(arr));
long int m = queries.size();
long int max = 0;
long int sum = 0;
for(int i=0;i<m;i++)
{
long int a = queries[i][0];
long int b = queries[i][1];
long int k = queries[i][2];
arr[a-1] += k;
arr[b] -= k;
}
for(int x=0;x<n;x++)
{
sum += arr[x];
if(max < sum)
max = sum;
}
return max;
Addition needs to be done at a and subtraction at b+1.
Also,avoid memset on hackerrank sometimes it doesn't work fine.
Lastly,the final loop would run till <=n.
Array Manipulation
You are viewing a single comment's thread. Return to all comments →
Hi. As for why we subtract k, I just added a detailed example to help answer your question in my original post.
Regarding the exact values of a and b, it's a little tricky since a and b are 1-indexed but our array is 0-indexed. So we want to subtract 1 from both a and b. However, for b we re-add 1 because we want to change values from a to b inclusive as stated in the problem, so we want the end of the interval to be 1 to the right of b which is why we re-add the 1.
Hope this helps.
HackerRank solutions.
can u guyz tell me whats wrong in my code?
long arrayManipulation(int n, vector> queries) {
}
Addition needs to be done at a and subtraction at b+1. Also,avoid memset on hackerrank sometimes it doesn't work fine. Lastly,the final loop would run till <=n.
actually this code works fine in 1st 3 test cases... and my code is for 0-indexed that is why I used a-1 and b does it wrong?