• + 13 comments

    Instead of storing the actual values in the array, you store the difference between the current element and the previous element. So you add sum to a[p] showing that a[p] is greater than its previous element by sum. You subtract sum from a[q+1] to show that a[q+1] is less than a[q] by sum (since a[q] was the last element that was added to sum). By the end of all this, you have an array that shows the difference between every successive element. By adding all the positive differences, you get the value of the maximum element

    • + 3 comments

      Important points to note in this solution.

      1)the first element of array a will always remain zero since 1<= a <=b <=n; 2

      2)the second element of array a is the second element of the array after m operations.

      • + 32 comments

        Same solution translated in python -

        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)
        
        • + 4 comments

          And the same approach in ruby -- I claim no credit for working this out -- I wrote this after reading the comments and code posted here.

          Just thought I'd add a ruby solution for anyone looking for one.

          N, M = gets.chomp.split(' ').map(&:to_i)
          
          # create array of zeros of length N + 1
          arr = Array.new(N + 1, 0)
          
          M.times do
              # cycle through and get the inputs
              start, finish, value = gets.chomp.split(' ').map(&:to_i)
          
              # increment value at start of sequence
              arr[start - 1] += value
          
              # decrement value at first position after sequence
              arr[finish] -= value
          end
          
          tmp = 0
          max = 0
          
          arr.each do |value|
              # step through summing array
              tmp += value
          
              # capture the max value of tmp
              max = tmp if max < tmp
          end
          
          puts max
          
          • + 13 comments

            Same solution in C

            int main() {
                long long int n,k,i,max=0,x=0;
                scanf("%lld %lld",&n,&k);
                int *a=(int *)malloc(sizeof(int)*(n+1));
                for(i=0;i<n;i++){
                  *(a+i)=0;
                }
                for(i=0;i<k;i++){
                    long long int c,d,g;
                    scanf("%lld %lld %lld",&c,&d,&g);
                    *(a+c)+=g;
                    if(d+1<=n){
                        *(a+d+1)-=g;
                    }
                    
                }
                for(i=1;i<=n;i++){
                    x+=*(a+i);
                    if(max<x){
                        max=x;
                    }
                }
                printf("%lld",max);
            		
                /* Enter your code here. Read input from STDIN. Print output to STDOUT */
                return 0;
            }
            

            Edit 1: I had used pointers so much because I was learning about pointers at that time

            Edit 2: Many were asking about the logic, I will try to give you the intuition The basic idea is doing lazy update,i.e., not doing actual update of range every time and instead store the net update somwhere so that it can be easily done in one go

            Suppose we have an array 3,2,4,5,7,9,4 and we want to make update, from 0 to 2 increase value by 1 We create update arr of equal size filled with 0 . For first update, update[0]+=1 and update[3]-=1. We add where the interval begins, we subtract just after the interval ends which just helps in excluding all indices from 3 and after that from being incremented. How so? When we have to do final update, we actually sum values from left. After suming values from left(update[i]+=update[i-1]) and filling update array you would get, update = [1,1,1,0,0,0,0]. Notice that we succesfully excluded all indices from 3 and after. If we hadn't subtracted at position 3, the whole update array would have been filled with 1. Similarly we can make more range updates using same logic. Sum at each index gives the net value to be updated. Hope this helps!

            • + 11 comments

              Same solution in C#

              using System;
              using System.Collections.Generic;
              using System.IO;
              class Solution {
                  
                  static void Main(String[] args) {
                      
                      string[] inString = Console.ReadLine().Split(' ');
                      uint[] initParams = Array.ConvertAll(inString, UInt32.Parse);
                      uint n = initParams[0];
                      uint m = initParams[1];
                      
                      long[] numList = new long[n+1];
                      
                      for(int i=0; i<m; i++)
                      {
                          string[] opString = Console.ReadLine().Split(' ');
                          uint a = UInt32.Parse(opString[0]);
                          uint b = UInt32.Parse(opString[1]);
                          long k = long.Parse(opString[2]);
                          
                          numList[a] += k;
                          if(b+1 <= n) numList[b+1] -= k;
                      }
                      
                      long tempMax = 0;
                      long max = 0;
                      for(int i=1; i<=n; i++)
                      {
                          tempMax += numList[i]; 
                          if(tempMax > max) max = tempMax;
                      }
                      
                      Console.WriteLine(max.ToString());
                  }
              }
              
              • + 24 comments

                Same solution in Java

                Scanner scan = new Scanner(System.in);
                int n = scan.nextInt();
                int m = scan.nextInt();
                        
                //This will be the "difference array". The entry arr[i]=k indicates that arr[i] is exactly k units larger than arr[i-1]
                long[] arr = new long[n];
                        
                int lower;
                int upper;
                long sum;
                
                for(int i=0;i<n;i++) arr[i]=0;
                
                for(int i=0;i<m;i++){
                    lower=scan.nextInt();
                    upper=scan.nextInt();
                    sum=scan.nextInt();
                    arr[lower-1]+=sum;
                    if(upper<n) arr[upper]-=sum; 
                }
                        
                long max=0;
                long temp=0;
                
                for(int i=0;i<n;i++){
                    temp += arr[i];
                    if(temp> max) max=temp;
                }
                
                System.out.println(max);
                
                • + 1 comment
                  [deleted]
                  • + 1 comment

                    It is the same logic as mentioned above.

                    • + 4 comments

                      Hi i dont understand how the difference array works. What is the logic behind adding at one index and subtracting at the other and taking its sum?

                      • + 3 comments

                        You can try to visualize the array as steps / stairs

                        We are just noting down the bump ups and bump downs

                        • + 3 comments

                          I still havent understood this logic.Even though i implemented this logic in java with ease,i dont understand how this logic helps us arrive at the solution.

                          • + 2 comments

                            me netheir, I am looking for the maths here, I am pretty sure the solution has a math method. Somebody here wrote "Prefix sum".

                            • + 0 comments

                              I tried an answer in the spirit of digital signal processing here.

                            • [deleted]
                              + 11 comments

                              After thinking like that i also understood the logic the solution.

                              Let's think our summing part input like that {A B S} = {1 3 100} {2 5 150} {3 4 110} {2 4 160}

                              Instead of writing all elements of array we can write maximum value at just starting and ending indexes to have less writing operation. So, after first input row, array can be something like that.

                              0 100 0 100 0 0 0 0 0

                              But the problem is here that even we didn't write anything, value of index 2 is also 100. When we wanted to continue with second step we have to check whether index 2 is between indexes of first row operation or not.

                              Instead of doing like that we can write S value to index A and -S value to B+1, so it is still similar logic. Starting from A to B all indexes have S value and rest of them have less than these indexes as S as. Now the array is like that:

                              0 100 0 0 -100 0 0 0 0

                              While calculating second row, we are writing 150 to index 2 and -150 to index 6. It will be like that: 0 100 150 0 -100 0 -150 0 0

                              If we write array with old method, which means that all numbers calculated one, it will be: 0 100 250 250 150 150 0 0 0

                              It shows that value of index 2 is : 100+150 = 250. Value of index 5: 100 + 150 + (-100) = 150. So by calculating with the solution written above, instead of writing all numbers, we are writing changes at edge indexes.

                              • + 2 comments

                                check it out here, you will get all your doubts solved https://www.geeksforgeeks.org/difference-array-range-update-query-o1/

                                • + 2 comments

                                  Below link will also help to understand theory behind it. https://www.geeksforgeeks.org/constant-time-range-add-operation-array/

                                  • + 10 comments

                                    Same solution in Javascript

                                        var arr = [];
                                        var max = 0;
                                        // init each element of arr to 0
                                        for (let l = 0; l < n; l++) {
                                            arr[l] = 0;
                                        }
                                        // for each sum operation in queries
                                        for (let i = 0; i < queries.length; i++) {
                                           // update arr with number to add at index=queries[i][0]  and number to remove at index=queries[i][0]+1 => this will allow us to build each element of the final array by summing all elements before it. The aim of this trick is to lower time complexity
                                            arr[queries[i][0]-1] += queries[i][2];
                                            if (queries[i][1] < arr.length) {
                                                arr[queries[i][1]] -= queries[i][2];
                                            }
                                        }
                                        for (let j = 1; j < n; j++) {
                                            arr[j] += arr[j-1];
                                        }
                                        for (let k = 0; k < arr.length; k++) {
                                            max = Math.max(max, arr[k]);
                                        }
                                        //max = Math.max(...arr); // not working for big arrays
                                        return max;
                                    
                                    • + 1 comment

                                      Hey, I did the code in Java8 and my code is getting failed for input type - where only single value is present in a row of array. meaning only left index value is provided and right and k value is missing from array. So can you help me how to solve this issue?

                                      • + 0 comments

                                        you could post your code,and we can check it out

                                    • + 3 comments

                                      simpler in es6:

                                      function arrayManipulation(n, queries) { let arr = new Array(2*n).fill(0); let max = 0;

                                      queries.forEach((item) => {
                                          arr[item[0]] += item[2];
                                          arr[item[1] + 1] -= item[2];
                                      });
                                      
                                      arr.reduce((prev, curr, idx) => {
                                          const sum = prev + curr;
                                          if (sum > max) {
                                              max = sum;
                                          }
                                      
                                          return sum;
                                      })
                                      
                                      return max;
                                      

                                      }

                                      • + 1 comment

                                        I did something pretty similar, just with a little bit more readable forEach:

                                        const arr = new Array(n).fill(0);
                                        let result = 0;
                                        
                                        queries.forEach(([a, b, k]) => {
                                            arr[a - 1] += k;
                                            if (b < arr.length) {
                                                arr[b] -= k;
                                            }
                                        });
                                        
                                        arr.reduce((a, b) => {
                                            const acc = a + b;
                                            result = Math.max(result, acc);
                                            return acc;
                                        }, 0);
                                        
                                        return result;
                                        
                                        • + 3 comments

                                          This produces wrong answer in some of the tests.

                                          • + 2 comments

                                            Hi,

                                            try this. Here is the video tutorial for my solution O(n+m) complexity.

                                            https://www.youtube.com/watch?v=hDhf04AJIRs&list=PLSIpQf0NbcCltzNFrOJkQ4J4AAjW3TSmA

                                            Would really appreciate your feedback like and comment etc. on my video.

                                            • + 1 comment

                                              It is a good video. I understood the algorithm clearly.

                                              • + 1 comment

                                                thanks @chandraprabha90.

                                                but it would be great if you can please provide your comments, like, dislike on my video how i did it..It motivates me to create better content for my audience.

                                                • + 2 comments

                                                  Could you add subtitles? I tried watching it but couldn't quite understand your accent through the audio

                                                  • + 0 comments

                                                    Hi Grozny,

                                                    I appologize for my bad sound quality but i am trying to improve it. but it will be very difficult to add subtitle for this video because its around half an hour which explains all the concepts in deep.

                                                    Making this long video took lot of effort and time now adding a subtitle will be very tedious without any support.

                                                    Will suggest you to try automatic transcribe feature from youtube to translate it.

                                                    Anyway thanks for watching.

                                                  • + 0 comments

                                                    Hi Grozny,

                                                    I have added subtitle for this tutorial and I hope it will you to understand logic with more clarity.

                                            • + 1 comment
                                              [deleted]
                                              • + 0 comments

                                                Nice approach you got there!

                                          • + 0 comments

                                            I had the same issue. my mistake was decrementing lower and upper. you don't decrement upper, the difference array needs to show it went down AFTER then last index, not within.

                                      • + 0 comments

                                        Thought to myself ....no js solutions here? then I find 3 of them, Js, ES6, readable wow.

                                    • + 0 comments

                                      Your last for loop isn't needed. You can move Math.max to the previous for loop.

                                    • + 0 comments

                                      Added some ES6 syntax suger...

                                      const arrayManipulation2 = (n, queries) => {
                                        const arr = new Array(n).fill(0);
                                        let max = 0;
                                        for (let i = queries.length - 1; i >= 0; i--) {
                                          const [a, b, k] = queries[i];
                                          arr[a - 1] += k;
                                          if (b < arr.length) {
                                            arr[b] -= k;
                                          }
                                        }
                                        for (let j = 1; j < n; j++) {
                                          arr[j] += arr[j - 1];
                                        }
                                        for (let k = arr.length - 1; k >= 0; k--) {
                                          max = Math.max(max, arr[k]);
                                        }
                                        return max;
                                      };
                                      
                                    • + 0 comments

                                      Got stuck because of this

                                      max = Math.max(...arr); // not working for big arrays

                                      Thanks man!

                                    • + 0 comments

                                      You could simplify your code a smidge, and save a little processing power, by removing your final for loop, and putting in an if check in the second to last loop, like this:

                                      for (let j = 1; j < n; j++) {
                                      	arr[j] += arr[j-1];
                                      	
                                      	if (arr[i] > biggest) {
                                      		biggest = arr[i];
                                      	}
                                      }
                                      
                                    • + 1 comment
                                      [deleted]
                                      • + 0 comments

                                        Perfect! Could you please explain me the thought process behind the solution?

                                    • + 0 comments

                                      My js solution ran out of time for a few test cases

                                      function arrayManipulation(n, queries) { let a = new Array(n).fill(0); for(let j = 0; j < queries.length; j++) { let temp = queries[j] let k = temp[0]; while(k <= temp[1]) { a[k-1] += temp[2]; k++; }

                                      } return Math.max.apply(Math, a); }

                                  • + 0 comments

                                    this one is the one that finally made it click for me...crazy how many different explanations are "whoosh" until the right person finds the "right" explanations.

                                    But let's keep doing standardized testing in schools /s

                                • + 0 comments

                                  Thanks for the post, it really made me understand the logic clearly

                              • + 0 comments

                                Thank you @Kemal_caymaz for the explanation, I have found this very useful.

                              • + 0 comments

                                Thank you!

                              • + 0 comments

                                thnx

                              • + 1 comment

                                super awesome X 1000!!!

                                can you expalin this: But the problem is here that even we didn't write anything, value of index 2 is also 100. When we wanted to continue with second step we have to check whether index 2 is between indexes of first row operation or not.

                                • + 2 comments

                                  Hi,

                                  I have created a video tutorial for you and uploaded the same on youtube. Here is the video tutorial for my solution O(n+m) complexity.

                                  https://youtu.be/hDhf04AJIRs

                                  Would really appreciate your feedback like, dislike , comment etc. on my video.

                                  • + 1 comment

                                    fantastic video, thank you!

                                    • + 0 comments

                                      most welcome.

                                      but if you dont mind can you please leave the same comment along with like, dislike on my video. it motivates me and help others too find the solution over internet.

                                  • + 0 comments

                                    impressive ...

                              • + 0 comments

                                thanks bro..

                              • + 0 comments

                                Hi,

                                Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                                I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

                                Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                                https://youtu.be/hDhf04AJIRs

                                Would really appreciate your feedback like, dislike , comment etc. on my video.

                              • + 1 comment

                                Thanks a lot budy for your fantastic explanation ! Your thinking is really amazing like you . Good job.

                                • + 0 comments

                                  most welcome. It would be great, if you can provide your feedback like, dislike , comment etc. on my video. It motivate me to do more for you all

                              • + 1 comment

                                hey used this logic its failing for 10 test cases with large inputs

                                • + 0 comments

                                  Hi,

                                  Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                                  I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

                                  Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                                  https://youtu.be/hDhf04AJIRs

                                  Would really appreciate your feedback like, dislike , comment etc. on my video.

                              • + 0 comments

                                Thanks, your explanation is very helpful

                              • + 0 comments

                                Thank you so much for clearly explaining this.

                          • + 1 comment

                            did you got it?

                            • + 0 comments

                              getting it correct for few cases but when both indexes are same then its giving a error message

                          • + 0 comments

                            How can you implement the logic with ease without understanding the logic? Copy and pasting is not the same as "implementing"

                        • + 0 comments

                          To explain further for people confused:

                          We are creating a "difference array" Which shows how many steps up or down have occurred (the difference between 0 and result of each operation) and where in the array they have occurred. This way, you can see how high the max ends up and return that for the solution.

                          I found this explanation helpful to have this fact dawn on me after much noodling: https://www.geeksforgeeks.org/difference-array-range-update-query-o1/

                        • + 0 comments

                          Like piling up blocks? Adding a number -> going up one step and subtracting -> down . Finally, we count how high we can go.

                      • + 2 comments

                        I'm still trying to figure it out myself. But if you graph result after doing the operations, you would see some rise and fall in the graph.

                        It looks like his solution tracks the differences between each data point. It went up by x, down by y, remained the same...etc. And his solutions finds the highest increase.

                        Example: 5 3
                        1 2 100
                        2 5 100
                        3 4 100

                        After doing the operations you get [100, 200, 200, 200, 100] His solutions final array is [0, 100, 100, 0, 0, -100] Meaning starting at 0 the graph went up by 100, went up by 100 again, remained the same, then went back down by 100.

                        So the highest point is 200, the solution.

                        • + 0 comments

                          you add up all the numbers > 0 in the final list, which is 100 + 100 = 200

                        • + 1 comment
                          [deleted]
                          • + 0 comments

                            Hi,

                            I have created a video tutorial for you and uploaded the same on youtube. Here is the video tutorial for my solution O(n+m) complexity.

                            https://youtu.be/hDhf04AJIRs

                            Would really appreciate your feedback like, dislike , comment etc. on my video.

                      • + 1 comment

                        One insight that might help is that we're keeping track of the change in values rather than the values themselves at each index. Therefore, by adding the k at a and subtracting it after b, we are saying that at a the total value increases by k compared to the previous element, and after b the total value decreases by k compared to b. Hope that helps!

                        • + 0 comments

                          Here's the same solution in swift in case anyone needs it :).

                          func arrayManipulation(n: Int, queries: [[Int]]) -> Int { var sums = Int: Int for query in queries { sums[query[0]] = (sums[query[0]] ?? 0) + query[2] sums[query[1] + 1] = (sums[query[1] + 1] ?? 0) - query[2] }

                          var currentmax = 0
                          var sum = 0
                          sums.sorted{ `$0.0 < $`1.0 }.
                              compactMap{ `$0.1; sum += $`0.1; currentmax = sum > currentmax ? sum : currentmax}
                          return currentmax
                          

                          }

                      • + 0 comments

                        refer to prefix sum algorithm.....you'll be clear!

                • + 1 comment

                  Hi , I have a doubt.

                  Here the indices are starting from 1. So, we should be subtracting 1 from both lower index and upper index. Here you have done so for lower index, but haven't done for upper index.

                  Can you please explain the reason behind this ?

                  • + 0 comments

                    It's because it doesn't go back down until the element after the section ends.

                    eg: n = 4, a = 1, b = 2 k = 3. So we have 3 3 0 0 after reading in that line. In his array he represents this as 3 0 -3 0 ie the subtraction is the element after the last element in the section.

                    The reason the lower value has a "-1" is because java uses 0-indexed arrays, ie they start at 0. But the input for this question only starts at 1. So he puts the values one index lower in the array. The upper value has no "-1" for the reason in the above paragraph about subtracting after the last element in the section

                • + 0 comments

                  You don't have to do this:

                  for(int i=0;i<n;i++) arr[i]=0;
                  

                  because long by default is 0

                • + 2 comments

                  could you please explain me the working of the code?

                  • + 0 comments

                    i think test code bigger than long int,so we need a larger data structure

                  • + 1 comment

                    Hi,

                    I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                    Here is the video tutorial for my solution O(n+m) complexity.

                    https://youtu.be/hDhf04AJIRs

                    Would really appreciate your feedback like, dislike , comment etc. on my video.

                    • + 0 comments

                      tnks @kanahaiya

                • + 0 comments

                  no need to init array elements to 0 in Java

                • + 1 comment

                  Hi, your solution works but I am not convinced!

                  I don't see how do you increment all elements between lower and upper!

                  • arr[lower-1]+=sum; This only increments the lower element by sum.
                  • if(upper
                  • arr[upper]-=sum; I don't understand why are you substructing sum!

                  Can you please explain? Thanks.

                  • + 1 comment

                    It's a difference array. He is storing the difference/the changes that should be made in each index and then runs a loop to add up all these changes. You increment the lower bound because everything inbetween the lower and upper bound should be incremented but you dont want this change to continue for the rest of the array so you decrement at (upper+1).

                    • + 0 comments

                      but how can we know about the upper index of a particular increment,when we are adding all at a once in a loop?

                • + 1 comment

                  Using Java 8 syntaxis:

                  public static void main(String[] args) {
                   Scanner in = new Scanner(System.in);
                   int n = in.nextInt();
                   int m = in.nextInt();
                   long[] output = new long[n];
                   IntStream.range(0,m).forEach(i -> { int a = in.nextInt()-1;
                                                      int b = in.nextInt();
                                                      int k = in.nextInt();
                                                      output[a] += k;
                                                      if(b < n) output[b] -= k; });
                   AtomicLong sum = new AtomicLong(0);
                   System.out.print(LongStream.of(output).map(sum::addAndGet)
                                                         .max().getAsLong());
                   in.close();
                  }
                  
                  • + 2 comments

                    large amount of lines will crash your solution. And map fucntion need to make Boxing methinks and this takes much time

                    • + 0 comments

                      WTF!!! It's true! I had a time out problem with test case 7 up to 12 I think and my code is good enough and didn't know what to do...until I read your comment, I removed all the empty spaces and the debugging prints (System.out.println for Java 8) and it worked :O LOL thanks.

                    • + 1 comment

                      This is true, I spent too much time trying figure out why my solution was timing out. Deleted some whitespace and it ran fine.

                      • + 0 comments

                        Hi,

                        I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                        Here is the video tutorial for my solution O(n+m) complexity.

                        https://youtu.be/hDhf04AJIRs

                        Would really appreciate your feedback like, dislike , comment etc. on my video.

                • + 0 comments

                  why temp += arr[i];

                • + 0 comments

                  Array is already 0, you dont have to assign 0s to each array elements

                • + 0 comments

                  scanner on large lines of input is not suitable solution, it reads too long

                • + 0 comments

                  You don't need to loop the arr to put 0. Bydefault, it has the value zero when you initialize.

                • + 0 comments

                  In java, we don't need to loop explicitly to assign zero to all the arr locations. When we create it, it has the zero as default values. I like your solution, thanks.

                • + 0 comments

                  using an if statement inside the for loop will just contribute in complexity. you can replace it with Math.max function.

                • + 2 comments

                  Is there a reason all the solutions posted above are written inside main() and not the provided function arrayManipulation() ? Or did hackerrank just change this over the past few years for readability?

                  // Complete the arrayManipulation function below.
                  static long arrayManipulation(int n, int[][] queries) {
                  
                  // initialize array with 0's of size n
                  long arr[] = new long[n];
                  
                  // each successive element contains the difference between itself and previous element
                  
                  for (int i = 0; i < queries.length; i++) {
                  // when checking query, subtract 1 from both a and b since 0 indexed array
                  int a = queries[i][0] - 1;
                  int b = queries[i][1] - 1;
                  int k = queries[i][2];
                  
                  arr[a] += k;
                  if (b+1 < n) {
                  arr[b+1] -= k;  
                  }
                  }
                  
                  // track highest val seen so far as we go
                  long max = Long.MIN_VALUE;
                  for (int i = 1; i < arr.length; i++) {
                  arr[i] += arr[i-1];
                  max = Math.max(arr[i], max);
                  }
                  
                  return max;
                  }
                  
                  • + 0 comments

                    Probably just for readability.

                  • + 0 comments

                    I was wondering the same thing. The instructions say to complete the manipulation method, not to rewrite the main method. I assumed that it should work without timing out if I just get the manipulation method to the point where it is efficient enough.

                • + 1 comment

                  Same solution in Golang

                  func arrayManipulation(n int32, qs [][]int32) int64 {
                  	a := make([]int64, n + 1)
                  	qLen := len(qs)
                  	for i:=0; i<qLen; i++ {
                  		p := int(qs[i][0])
                  		q := qs[i][1]
                  		sum := int64(qs[i][2])
                  		a[p] += sum
                  		if((q + 1) <= n) {
                  			a[q + 1] -= sum
                  		}
                  	}
                  
                  	var x, max int64 = 0, 0
                  	for i:=1; i<=int(n); i++ {
                  		x += a[i]
                  		if max < x {
                  			max = x
                  		}
                  	}
                  
                  	return max
                  }
                  

                  Clever solution!

                  • + 2 comments

                    Can you help me see what is wrong with my code here?

                    func arrayManipulation(n int32, queries [][]int32) int64 {
                        a := make([]int64, n + 1)
                        qLen := len(qs)
                        for i:=0; i<qLen; i++ {
                            p := int(qs[i][0])
                            q := qs[i][1]
                            sum := int64(qs[i][2])
                            a[p] += sum
                            if((q + 1) <= n) {
                                a[q + 1] -= sum
                            }
                        }
                    
                        var x, max int64 = 0, 0
                        for i:=1; i<=int(n); i++ {
                            x += a[i]
                            if max < x {
                                max = x
                            }
                        }
                    
                        return max
                    
                    }
                    
                    • + 0 comments

                      Wrong name in first line:

                      func arrayManipulation(n int32, queries [][]int32) int64 {

                      }

                    • + 0 comments

                      why it is a[q + 1] -= sum, it should be a[q + 1] += sum, right????

                • + 3 comments

                  import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.regex.*;

                  public class Solution {

                  // Complete the arrayManipulation function below.
                  static long arrayManipulation(int n, int[][] queries) {
                    int[] arr = new int[n];
                    for(int i=0;i<n;i++){
                      arr[i] = 0;
                    }
                    int m = queries.length;
                    for(int i=0;i<m;i++){
                      for(int j=queries[i][0]-1;j<queries[i][1];j++){
                        arr[j] += queries[i][2];
                      }
                    }
                    int max = arr[0];
                    for(int i=1;i<n;i++){
                      if(arr[i]>max){
                        max = arr[i];
                      }
                    }
                    return(max);
                  
                  
                  
                  
                  
                  
                  
                  
                  }
                  
                  private static final Scanner scanner = new Scanner(System.in);
                  
                  public static void main(String[] args) throws IOException {
                      BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
                  
                      String[] nm = scanner.nextLine().split(" ");
                  
                      int n = Integer.parseInt(nm[0]);
                  
                      int m = Integer.parseInt(nm[1]);
                  
                      int[][] queries = new int[m][3];
                  
                      for (int i = 0; i < m; i++) {
                          String[] queriesRowItems = scanner.nextLine().split(" ");
                          scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
                  
                          for (int j = 0; j < 3; j++) {
                              int queriesItem = Integer.parseInt(queriesRowItems[j]);
                              queries[i][j] = queriesItem;
                          }
                      }
                  
                      long result = arrayManipulation(n, queries);
                  
                      bufferedWriter.write(String.valueOf(result));
                      bufferedWriter.newLine();
                  
                      bufferedWriter.close();
                  
                      scanner.close();
                  }
                  

                  }

                  What is wrong with this code. Please help.

                  • + 0 comments

                    it may be showing Terminated due to timeout error because in test case 7 there is a huge number of input 10000000 100000 (like that)

                    you should try prefix array sum it is so simple

                  • + 2 comments

                    Hi,

                    Your solution is good but time complexity of your solution is O(n*m) which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                    Here is the video tutorial for my solution O(n+m) complexity.

                    https://www.youtube.com/watch?v=hDhf04AJIRs&list=PLSIpQf0NbcCltzNFrOJkQ4J4AAjW3TSmA

                    Would really appreciate your feedback like and comment etc. on my video.

                    • + 1 comment

                      your video is helpful

                      • + 1 comment

                        thanks. But if would be great ,if you can provide your comments, like, dislike on my video how i did it..It motivates me to create better content for my audience.

                        • + 1 comment

                          Your video helped me understand the algorithm. I liked the video. Thank you so much

                          • + 0 comments

                            thanks. But if would be great ,if you can provide your comments, like, dislike on my video how i did it..It motivates me to create better content for my audience.

                    • + 0 comments

                      Thanks @Kanahaiya for sharing. Your video is very helpful. I really liked the way you explained by dry running the solution. One of the best programming tutroial ever seen. Surely, will look into other videos as well.. Thanks.

                  • + 0 comments

                    you will get TLE. Try different algorithm which takes less time.

                • + 0 comments

                  Thanks for the clean code and the comment! It helped more than the entire discussion!

                • + 0 comments

                  This line is unnecessary due to the fact that the default value of long in Java is 0L and there is no need for assigning them again to 0.

                  for(int i=0;i<n;i++) arr[i]=0;

                • + 0 comments

                  Thanks for the enlightenment.

                  Here is the same solution in Swift:

                  func arrayManipulation(n: Int, queries: [[Int]]) -> Int {
                  
                      var numbers = Array(repeating: 0, count: n + 1)
                      var ans = 0
                  
                      for i in 0 ..< queries.count {
                          var a = queries[i][0]
                          var b1 = queries[i][1] + 1
                          var k = queries[i][2]
                  
                          numbers[a] += k
                          
                          if b1 <= n {
                              numbers[b1] -= k
                          }
                      }
                  
                      for i in 1...n {
                          numbers[i] += numbers[i - 1]
                  				
                          if numbers[i] > ans {
                              ans = numbers[i]
                          }
                      }
                  		
                      return ans
                  }
                  
                • + 0 comments

                  I think

                  for(int i=0;i

                  is not needed.

                • + 1 comment
                  [deleted]
              • + 2 comments

                Same solution in javascript

                function main() {
                    let n_temp = readLine().split(' ');
                    let n = parseInt(n_temp[0]);
                    let m = parseInt(n_temp[1]);
                    let res = [];
                    let sum = 0;
                    let max = 0;
                
                    for (let i = 0; i<n; i++) {
                        res[i] = 0;
                    }
                    
                    for(var a0 = 0; a0 < m; a0++){
                        var a_temp = readLine().split(' ');
                        var a = parseInt(a_temp[0]);
                        var b = parseInt(a_temp[1]);
                        var k = parseInt(a_temp[2]);
                
                        res[a-1] += k;
                        if (b<n) res[b]-=k;
                    }
                  
                    for (let i=0; i<n; i++) {
                        sum += res[i];
                        if (max < sum) max = sum;
                    }
                   
                    console.log(max);
                }
                
                • + 4 comments

                  very smart,here is follow output to help me understand the idea

                  Compilation Successful
                  Input (stdin)
                  5 1
                  1 2 100
                  Your Output (stdout)
                  Slope List [ 100, 0, -100, 0, 0 ]
                  Actual List[100,100,0,0,0]
                  
                  Compilation Successful
                  Input (stdin)
                  5 2
                  1 2 100
                  2 5 100
                  Your Output (stdout)
                  Slope List [ 100, 100, -100, 0, 0 ]
                  Actual List[100,200,100,100,100]
                  
                  
                  Compilation Successful
                  Input (stdin)
                  5 3
                  1 2 100
                  2 5 100
                  3 4 100
                  Your Output (stdout)
                  Slope List [ 100, 100, 0, 0, -100 ]
                  Actual List[100,200,200,200,100]
                  
                  • + 2 comments
                    process.stdin.resume();
                    process.stdin.setEncoding('ascii');
                    
                    var input_stdin = "";
                    var input_stdin_array = "";
                    var input_currentline = 0;
                    
                    process.stdin.on('data', function (data) {
                        input_stdin += data;
                    });
                    
                    process.stdin.on('end', function () {
                        input_stdin_array = input_stdin.split("\n");
                        main();
                    });
                    
                    function readLine() {
                        return input_stdin_array[input_currentline++];
                    }
                    
                    /////////////// ignore above this line ////////////////////
                    
                    function main() {
                        var n_temp = readLine().split(' ');
                        var listSize = parseInt(n_temp[0]);
                        var lineNumber = parseInt(n_temp[1]);
                        let slopList = new Array();
                        for(let i = 0;i < listSize;i++){
                            slopList.push(0);
                        }
                    
                        for(var a0 = 0; a0 < lineNumber; a0++){
                            var a_temp = readLine().split(' ');
                    
                            const beginElementPos = parseInt(a_temp[0]);
                            const endElementPos = parseInt(a_temp[1]);
                            const addValue = parseInt(a_temp[2]);
                            slopList[beginElementPos-1] += addValue;
                            if (endElementPos<listSize){
                              slopList[endElementPos]-=addValue;
                            }
                        }
                        let actualList = new Array();
                        let sum = 0;
                        for (let i=0; i<listSize; i++) {
                            sum += slopList[i];
                            actualList.push(sum);
                        }
                    
                       let max =  actualList.reduce((acc,val)=>{
                    
                            return (acc>val)?acc:val;
                        },0);
                        console.log(max);
                    
                    }
                    
                    • + 5 comments

                      Guys, if you look for a clear understanding of the solution, I read a pretty clear comment down the road that clarified my mind.

                      Basically, when you add value from a to b you just need to know that it goes up from k and goes down of k after.

                      What this algo does is to register the slopes only, so we just need 2 entry, with O(1) complexity.

                      We just need to know that we are upping from k at the beginning and decreasing at the end.

                      Finally, the maximum would be...

                      image

                      The addition of all the slopes, that is why it's max(sum) of the tables, because the tables itself registers the slopes

                      • + 1 comment
                        [deleted]
                      • + 0 comments

                        Thanks a lot!!That really helped!

                      • + 2 comments

                        Can you explain the concept of just adding add subtracting at a particular index? I mean how have we arrived to this logic?

                        • + 0 comments

                          Hi,

                          I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                          Here is the video tutorial for my solution O(n+m) complexity.

                          https://youtu.be/hDhf04AJIRs

                          Would really appreciate your feedback like, dislike , comment etc. on my video.

                        • + 1 comment

                          Hi,

                          Here is the video tutorial for my solution O(n+m) complexity.

                          https://youtu.be/hDhf04AJIRs

                          Would really appreciate your feedback like and comment etc. on my video.

                          • + 1 comment

                            I've add it to my playlist

                            • + 0 comments

                              haha..thank you.

                              but if you dont mind, Would really appreciate your feedback like, dislike , comment etc. on my video.

                      • + 3 comments

                        I didnt well understand that what will happen if b+1 is out of array bounds?

                        • + 0 comments

                          it can't be out of bounds, it saids that b>n in the problem statement.

                        • + 0 comments

                          if b+1 > n then the the addition of k from position a will continue till the last element of the array.

                        • + 0 comments

                          Hi,

                          I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                          Here is the video tutorial for my solution O(n+m) complexity.

                          https://youtu.be/hDhf04AJIRs

                          Would really appreciate your feedback like, dislike , comment etc. on my video.

                      • + 1 comment

                        Jesus christ, it all makes sense now after that graph lol, I kept wondering what drug these people were taking to arrive at this conclusion.

                        • + 0 comments

                          can you explain ? :)

                    • + 0 comments

                      Very well explained (Y)

                  • + 0 comments

                    i have got correct output of your test cases but 3 test cases of hackerrank are getting wrong. iam not understanding whats wrong.please help me

                  • + 0 comments

                    brilliant idea!

                  • + 1 comment

                    what about the custom input:

                    5 1

                    1 5 -100

                    wouldn't the output be 0? But the max would be -100 since all elements would be -100.

                    • + 0 comments

                      There's a constraint: 0 <= k <= 10^9

                      In your case of negative k, the minimum value can be obtained by the similar approach. Imagine a valley rather than a mountain.

                • + 0 comments

                  why are you subtracting???? "( b < n ) res [ b ] -= k;"

              • + 3 comments

                How is your method faster than the following?

                using System;
                using System.Collections.Generic;
                using System.IO;
                using System.Linq;
                using System.Numerics;
                
                class Solution {
                
                    static void Main(String[] args) {
                        string[] tokens_n = Console.ReadLine().Split(' ');
                        int n = Convert.ToInt32(tokens_n[0]);
                        int m = Convert.ToInt32(tokens_n[1]);
                        
                        // Instantiate and populate an array of size N
                        BigInteger[] arr = new BigInteger[n];
                        for(int i = 0; i < n; i++)
                            arr[i] = 0; 
                        
                        for(int a0 = 0; a0 < m; a0++){
                            string[] tokens_a = Console.ReadLine().Split(' ');
                            int a = Convert.ToInt32(tokens_a[0]);
                            int b = Convert.ToInt32(tokens_a[1]);
                            int k = Convert.ToInt32(tokens_a[2]);
                            
                            // Apply operation
                            for(int j = a-1; j < b; j++)
                                arr[j] += k; 
                        }
                        
                        Console.WriteLine(arr.Max(i=>i));
                    }
                }
                
                • + 0 comments

                  The "Apply operation part" is O(k) here. In the diff array version, apply operation is O(1)

                • + 1 comment

                  hey did u passed all with this...i used same logic in C#..but passes till 6

                  • + 0 comments

                    your database is int? some tests data is too big

                • + 1 comment

                  your code is only passing 3 test cases out of 10 . Don't post the code unless it pass all the test cases dude !!!!

                  • + 1 comment

                    bro, this is a discussion forum. Why are you demotivating a begineers ? Anyway I have submitted that code successfully. Thanks for the advice.

                    • + 1 comment

                      I used the same logic, it passes most of the tests but I get timeout error.

                      • + 0 comments

                        Hi,

                        I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                        Here is the video tutorial for my solution O(n+m) complexity.

                        https://youtu.be/hDhf04AJIRs

                        Would really appreciate your feedback like, dislike , comment etc. on my video.

              • + 0 comments

                if(b+1 <= n) numList[b+1] -= k;

                Why we are substracting?

              • + 0 comments

                It is failing test case 4 to 13. Not sure why

              • + 0 comments

                It is failing test case 4 to 13. Can you please check

              • + 0 comments
                long tempMax = 0;
                    long max = 0;
                    for(int i=1; i<=n; i++)
                    {
                        tempMax += numList[i]; 
                        if(tempMax > max) max = tempMax;
                    }
                
                            What is this code doing , why we cant use  numList.Sum()
                
              • + 0 comments

                Used the idea o modifiers, but without the n-sized array. Also in C#. Complexity is O(m log m), that can be less than O(n).

                static long arrayManipulation(int n, int m, int[][] queries) {
                    long max = 0;
                
                    SortedDictionary<int,long> fakeArray = new SortedDictionary<int,long>();
                
                    // 'm' times
                            for (int i=0; i<m; i++) {
                        int a = queries[i][0];
                        int b = queries[i][1];
                        int k = queries[i][2];
                
                        // bit optimization: a '0' valued query will make no difference on resultant ones
                        if (queries[i][2] <= 0) continue;
                
                        if (!fakeArray.ContainsKey(a)) {  // O( log m )
                            fakeArray.Add(a, k);                 // O( log m )
                        }
                        else {
                            fakeArray[a] += k;                    // O( log m )
                        }
                
                        if (b < n) {
                            b++;
                            if (!fakeArray.ContainsKey(b)) {   // O( log m )
                                fakeArray.Add(b, -1 * k);          // O( log m )
                            }
                            else {
                                fakeArray[b] -= k;                      // O( log m )
                            }
                        }
                    }
                
                    long current = 0;
                    foreach(long modifier in fakeArray.Values){ // O( 2*m )
                        current += modifier;
                        if (current > max) max = current;
                    }
                
                    return max;
                }
                
              • + 0 comments

                In the last for, i should be initialized to 0, not 1

            • + 1 comment

              *(a+c)+=g; if(d+1<=n){ *(a+d+1)-=g; }

                  please explain what's going on here.
              
              • + 0 comments

                This is a very elegant and beautiful solution.

            • + 1 comment

              could you please explain me the logic?

              • + 1 comment

                Hi,

                Most of the peope solved this problem but time complexity of your solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                I have created a video tutorial for you and uploaded the same on youtube. Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                https://youtu.be/hDhf04AJIRs

                Would really appreciate your feedback like, dislike , comment etc. on my video.

                • + 0 comments

                  Thanks, that helped understanding the optimization.

            • + 1 comment

              pls explain logic

              • + 0 comments

                Hi,

                Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

                Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                https://youtu.be/hDhf04AJIRs

                Would really appreciate your feedback like, dislike , comment etc. on my video.

            • + 1 comment
              [deleted]
              • + 0 comments

                Hi,

                I have uploaded a video tutorial which can help you to understand the problem as well as logic.

                Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                https://youtu.be/hDhf04AJIRs

                Would really appreciate your feedback like, dislike , comment etc. on my video.

            • + 0 comments

              Will fail if max result is negative

            • + 1 comment

              i cant pass some test cases, those with very long inputs, i dont know what to do! here is my code: -

              long arrayManipulation(long long int n, vector> queries) {

              vector<long long int> v;
              vector<long long int>v2;
              long long int max;
              
              for(long long int i=0;i<n;i++){
                  v.push_back(0);
              }
              for(long long int i=0;i<queries.size();i++){
              
                  for(long long int j=0;j<queries[i].size();j++){
                      v2.push_back(queries[i][j]);
                  }
              
                 for(long long int k=(v2[0]-1);k<v2[1];k++){
                     if(v[k]!=0){
                         v[k]+=v2[2];
                     }
                     else{
                         v[k]=v2[2];
                     }
                  }
                  v2.pop_back();
                  v2.pop_back();
                  v2.pop_back();
              }
              
              max=*max_element(v.begin(), v.end());
              return max;
              

              }

              • + 0 comments

                hi,

                I am sure this comment will definately help you.

                https://www.hackerrank.com/challenges/crush/forum/comments/570284

            • + 0 comments

              No need to explicitly assign 0 to every item in the array. malloc() does that automatically.

            • + 1 comment

              calloc would be faster i guess instead of malloc + zeroing the mem

              • + 1 comment

                Could you explain more, please?

                • + 1 comment

                  in the code there are two steps to acquire a new array filled with zeroes:

                  1. At first step the allocation itself: int *a=(int )malloc(sizeof(int)(n+1));
                  2. Second step is to propagate zero values using for-loop upon newly created array.

                  In my opinion, we can do the same with single call of "calloc". It supposed to be faster in theory, cause calloc is hardware dependent and probably we don't have to loop over N items again just for get them zero valued, since calloc could know is it actually required or not, so on some harware it could be already zeroes or hardware knows better how to zero during allocation faster

                  • + 0 comments

                    okay thanks for the information!

            • + 0 comments

              Can you please explain this code to me

          • + 0 comments

            This does not work for the current version of this problem. The prompt is asking for the solution of a method with two args, one n for the size ofthe array and a queries array of arrays with start index, end index, and value. There should be no need for gets.chomp().

          • + 0 comments

            And you can easily make solution "sparse" to conserve memory on big arrays, just replace

            arr = Array.new(N + 1, 0)

            with

            arr = Hash.new(0)

            and

            arr.each do |value|

            with

            1.upto(N) do |n| value = arr[n]

          • + 0 comments

            Here, an easiest way to understand in ruby, at least for me.

            def arrayManipulation(n, queries)
                arr = Array.new(n + 1, 0)
                queries.each do |q|
                    arr[q.first - 1] += q.last
                    arr[q[1]] -= q.last
                end
                tmp = 0
                max = 0
                arr.each do |n|
                    tmp += n
                    max = tmp if tmp > max
                end
                max
            end
            
        • + 1 comment

          This worked, but I'm still trying to understand why this was the correct answer.

          • + 1 comment

            Because it takes less time to execute. Otherwise solution execution got time outed

            • + 1 comment

              You are not answering the question.

              • + 1 comment

                I believe what he's trying to say is this: There are two approaches here - 1. The difference array approach (the one every one is praising as being more efficient) 2. The intuitive approach - i.e., just going through each group of a,b,k values and incrementing elements located between a and b in the array, then finally searching through for a max)

                The reason approach 1 is more efficient is because the operation for the difference array only requires a maximum 2 adjustments per transformation (you increment the value at the start index by k, and decrement the value after the end index by k). Contrast this with approach 2, where actually going through the array and incrementing every value within the specified 'a-b' range could result in N operations.

                So approach 2 could take a max of O(N * M) time- where 'M' is the number of operations, and N is the size of the array And approach 1 could take a max of O(2 * M) time, which is considered equivalent to O(M)

                Does that make sense? Someone correct me if I'm wrong! Cheers :)

                • + 1 comment

                  Yeah, if we went with the brute force solution with two nested for loops, we will get a graph as below for the array if we used the data below

                  arrayManipulation(40,[[19, 28, 419],
                  [4, 23, 680],
                  [5, 6, 907],
                  [19, 33, 582],
                  [5, 9, 880],
                  [10, 13, 438],
                  [21, 39, 294],
                  [13, 18, 678],
                  [12, 26, 528],
                  [15, 30, 261],
                  [8, 9, 48],
                  [21, 23, 131],
                  [20, 21, 7],
                  [13, 40, 65],
                  [13, 23, 901],
                  [15, 15, 914],
                  [14, 35, 704],
                  [20, 39, 522],
                  [10, 18, 379],
                  [16, 27, 8],
                  [25, 40, 536],
                  [5, 9, 190],
                  [17, 20, 809],
                  [8, 20, 453],
                  [22, 37, 298],
                  [19, 37, 112],
                  [2, 5, 186],
                  [21, 29, 184],
                  [23, 30, 625],
                  [2, 8, 960]])
                  

                  but if we used the second method which is adding at the first index and subtracting at the index afer the last we get this graph

                  and then we can get the maximum out of summing the results as below

                  • + 2 comments

                    but I can't understand the logic of least step ( summing step )

                    • + 2 comments

                      the best way to understand it is form a simple example.

                      say there are 4 of us in a line: 1. me 2. you 3. bob 4. sue and we all start out with zero points.

                      Thcan be represented as (where my points are in the first index, your in the second, bob's in the third, sue's in fourth):

                      0 0 0 0

                      Furthermore, we go through rounds, where in each round a contiguous block of us can receive some set amount of points.

                      So in round one, say 2 points are awarded to anything in the range of start index = 1, and end index = 2. This means that you and bob, who are in the range, get 2 points.

                      But rather than write the current score as: 0 2 2 0

                      We instead want to write the score as:

                      0 2 0 -2

                      Because we want each value to represent how much greater/less than it is from the previous-index value. Doing this allows us to only ever need to change two elements in the list for a given round.

                      Now say we play one more round, and 1 point is awarded to all people in range of index = 0 to index = 1. This gives you

                      1 2 -1 -2

                      All I did was add the point value to the start index, and subtract it from the "end index + 1".

                      Then calculating the max is simply a matter of going through that list, adding each element to an accumulator variable (as this summing process reveals the actual value of an element at any given point - e.g., you would have 3 points at the end because your score is the result of 1 + 2), and having a variable which keeps track of the running max.

                      • + 0 comments

                        Thank you for your detailed explanation. It helped!

                      • + 0 comments

                        Because we want each value to represent how much greater/less than it is from the previous-index value.

                        This is the best explanation of the difference array I have read in these discussions -- thank you for making it click in my head.

                    • + 0 comments

                      Hi,

                      Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

                      I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

                      Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

                      https://youtu.be/hDhf04AJIRs

                      Would really appreciate your feedback like, dislike , comment etc. on my video.

        • + 1 comment

          I would not suggest eclipsing list

          • + 2 comments

            Can some one please help as to why my solution gives a segmentation fault?

            include

            include

            include

            include

            int main() {

            unsigned long long int n,m,l,b,k,i,val=0;
            scanf("%llu%llu",&n,&m);
            unsigned long long int a[n+1];
            for(i=1;i<=n;i++)
            {
               a[i]=0;    
            }
            while(m--)
            {
                scanf("%llu%llu%llu",&l,&b,&k);        
                for(i=l;i<=b;i++)
                {
                   a[i]+=k;    
                   if(a[i]>val)
                   {
                       val=a[i];
                   }
                }
            }
            printf("%llu",val);
            return 0;
            

            }

            • + 1 comment

              Maximum array size has to be 10^7 which is not possible in case of C. I tried Dynamic memory allocation (malloc) which worked but got TLE for bigger test cases

              • + 0 comments

                yeah it is getting a tle. We need to use a different algorithm. I wanted to know what the problem in my code was so i posted my solution.

            • + 0 comments

              use long instead of int.

        • + 1 comment

          Hi Vineet could u explain what logic have you followed?

          • + 0 comments

            Hi,

            Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

            I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

            Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

            https://youtu.be/hDhf04AJIRs

            Would really appreciate your feedback like, dislike , comment etc. on my video.

        • + 5 comments

          Same solution but optimized:

          from itertools import accumulate
          
          n, m = map(int, input().split(' '))
          dx = [0] * (n + 1) # allow run past end
          
          for _ in range(m):
              a, b, c = map(int, input().split(' '))
              dx[a - 1] += c
              dx[b] -= c
          
          print(max(accumulate(dx)))
          
          • + 0 comments

            That's so good! You are awesome!

          • + 1 comment

            can you explain why it's (n+1) and not (n)?

            • + 0 comments

              The question asks for a 1 indexed list and the a,b values read in are read in starting from 1 not 0. If you do not use (n+1)if b happens to be the last number of your list it will go out of bounds.

              The 0 index value will always be 0 so it doesn't affect your answer when you sum for max difference.

          • + 1 comment

            why are you subtracting dx[b] -= c ?????

            • + 0 comments

              Walk through the array it may help.

              Query 1 -> [1, 2, 100] Array 1 -> [0, 100, 0, -100, 0, 0, 0] Query 2 -> [2, 5, 100] Array 2 -> [0, 100, 100, -100, 0, 0, -100] Query 3 -> [3, 4, 100] Array 3 -> [0, 100, 100, 0, 0, -100, -100] Array Accumulated -> [0, 100, 200, 200, 200, 100, 0] Result -> 200

          • + 0 comments

            The use of accumulate is so brilliant!

          • + 0 comments

            Nice

        • + 0 comments

          How does that bottom for list return the maximum value in the list? Could you explain the logic to me please?

        • + 0 comments

          Why are you checking if "y" is <= len(list) ? This is given by the problem, right?

        • + 0 comments

          Really liked this solution! One question, shouldn't it be max=-float('inf')?

          P.S - Talking about the python version

        • + 0 comments

          Just improved your code a bit. - split() is slightly faster than split("") - an if was not needed as always true - variables names fit those used in the exercise

          if __name__ == "__main__":
              n, m = [int(n) for n in input().split()]
              l = [0]*(n+1)
              for _ in range(m):
                  a, b, k = [int(n) for n in input().split()]
                  l[a-1] += k
                  l[b] -= k;
              max = a = 0
              for i in l:
                 a+=i;
                 if max<a:
                      max=a;
              print(max)
          
        • + 0 comments

          I took the ideas explained here to put also into python in a bit more spelled-out way to help make sense of this more abstract work-around.

          def arrayManipulation(n, queries):
                  # Big O (N)
                  res = [0]*(n+1) # we only really need one terminal row, since we're applying each pass to all rows below
          
                  # loop through all the queries and apply the increments/decrements for each
                  # Big O (M) (size of queires)
                  for row in range(len(queries)):
                          a = queries[row][0]
                          b = queries[row][1]
                          k = queries[row][2]
          
                          res[a-1] += k # increment the starting position
                          # this is where a loop would increment everything else between a & b by k
                          # but instead of taking b-a steps, we take a constant 2 steps, saving huge on time
                          res[b] -= k # decrement the position AFTER the ending position
          
                  # now loop through res one time - Big O (N) (size of res)
                  sm = 0 # running sum
                  mx = 0 # maximum value found so far
                  for i in range(len(res)):
                          sm += res[i]
                          if sm > mx:
                                  mx = sm
          
                  # total run time is Big O (2*N + M) >> Big O(N)
                  return mx
          

          The key concepts in my opinion here are:

          1) we don't need to build the full aray, since it's impossible for any row but the last to have the max value. This is impossible because we apply the adjustments to every subsequent row of the resulting 2-D array.

          2) we don't need to actually increment each value for indices 'a' through 'b'. While that's the most straight-forward way, that also requires x many (a minus b) steps for each pass of the loop. By noting instead where to start incrementing and where to stop incrementing (noted by decrementing after what would be the final increment), we can note the adjustments to apply without having to take every step each time. We can then run a separate single loop to go over each of the increments and keep a running sum of all the overlapping increments. The decrement allows us to know when that range where the increment applied is over by reducing the running sum by that number - in other words when that range is ended, we would have to look at overlapping increments excluding that one that just ended going forward to see if anything is bigger.

          Someone else in here gave an image of a stair/hill which I found extremely helpful in visualizing and understanding this concept. The basic idea here is that instead of actually applying each increment, we can just note what the increment and range is and one by one go through each place and apply all the compounded increments at once. Loop 1 saves the increments in a different format, Loop 2 checks the overlap. And by using two separate loops we have basically Big O (N) rather than Big O (N^2) - or more specifically Big O (2N + M) instead of Big O (NM + N), where N is the size of the resulting array and M is the size of the queries array.

        • + 0 comments

          def arrayManipulation(n, queries): arr=[0]*n for _ in queries: start=[0]-1 end=[1]-1 val=_[2] topVal=end+1 for i in range(start,topVal): arr[i]+=val return max(arr)

          m = input().split()

          n = int(nm[0])

          m = int(nm[1])

          queries = []

          for _ in range(m): queries.append(list(map(int, input().rstrip().split())))

          result=arrayManipulation(n, queries)

        • + 0 comments

          not sure why, but when I run your code as it is I get an error: if((y)<=len(list)): list[y] -= incr; IndexError: list index out of range

          but when I do run that line like this:

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

          that works

        • + 0 comments

          A bit less efficient, but more readable

          def arrayManipulation(n, queries):
              a = [0] * (n + 1)
              for q in queries:
                  a[q[0] - 1] += q[2]
                  a[q[1]] -= q[2]
          
              for i in range(1, len(a)):
                  a[i] += a[i-1]
          
              return max(a)
          
        • + 3 comments

          Python 3 more clear code

          def arrayManipulation(n, queries):
              
              my_array = [0] * (n+1)
              count = 0
              temp = 0
              for first,last,value in queries:
                  
                  my_array[first-1] += value
                  my_array[last] -= value
              
              for item in my_array:
                  count += item
                  if count > temp:
                      temp = count
                 
              return temp
          
          • + 2 comments

            can you explain your logic ??

            • + 0 comments

              Hi,

              Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

              I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

              Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

              https://youtu.be/hDhf04AJIRs

              Would really appreciate your feedback like, dislike , comment etc. on my video.

          • + 0 comments

            Thank you. This is clear.

            You could also find the max using: max(accumulate(my_array))

            See below:

            def arrayManipulation(n, queries):
                # initialise list
                arr = [0] * (n + 1)
            
                # update
                for a, b, k in queries:
                    arr[a - 1] += k
                    arr[b] -= k
                
                # accumulate values
                return max(accumulate(arr))
            

            However, I have not understood the theory behind the difference array algorithm, why it works the way it works and how to derive it.

          • + 1 comment

            can anyone debug this program

        • + 1 comment

          Brilliant man, mine was working for initial test cases but getting timeout for rest.

          def arrayManipulation(n, queries):
              a = [0]*(n +1)
              z=[]
              for i in queries:
                  z.append(i)
              for i in range(len(z)):
                  for j in range(int(z[i][0]),int( z[i][1])+1):
                      a[j] = a[j]+int ( z[i][2])
              return max(a)
          
          • + 0 comments

            Hi,

            Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

            I have created a video tutorial for you and uploaded the same on youtube with complete explanation along with code complexity analysis.

            Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

            https://youtu.be/hDhf04AJIRs

            Would really appreciate your feedback like, dislike , comment etc. on my video.

        • + 0 comments

          Thanks , max(list) wil be simpler

        • + 1 comment

          can the same be written like this: def arrayManipulation(n, queries): arr_n=[0]*n for i in range(len(queries)): n1=queries[i][0] n2=queries[i][1] for j in range(n1-1,n2): arr_n[j]=arr_n[j]+queries[i][2] return max(arr_n) This is giving me a tiemout error while submitting. can u assist here?

          • + 0 comments

            yeah,at the beginning, l got the same problem as well. This algorithm's complexity could be o(n). Try to learn something about prefix sum array.I hope this can help.

        • + 0 comments

          But when y=len(list), list(y) will throw an error right? out of index error?

        • + 1 comment

          Another python translation:

          def arrayManipulation(n, queries):
              arr = [0]*(n+2)
              for a, b, k in queries:
                  arr[a]+=k
                  arr[b+1]-=k
              result = acc = 0
              for x in arr:
                  acc+=x
                  result = max(result, acc)
              return result
          
          • + 0 comments

            Brilliant!

        • + 1 comment

          can u explain why we are subracting i dont understand the if statement ......

          • + 0 comments

            Hi,

            I have uploaded a video tutorial which can help you to understand the problem as well as logic.

            Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

            https://youtu.be/hDhf04AJIRs

            Would really appreciate your feedback like, dislike , comment etc. on my video.

        • + 0 comments

          This breaks when y == n. The if when decrementing list[y] should be if y < len(list): list[y] -= incr. Overall great solution! Thanks for doing it in python!

        • + 0 comments

          Excellent, but why you are using this step.. list[y] -= incr; and that "if" condition is always correct, right..! Can you explain please...

        • + 0 comments

          for some test cases its showing teminated due to timeout what can i do

          def arrayManipulation(n, queries):
              a=[]
              for i in range(n):
                  a.append(0)
              for j in queries:
                  for k in range(j[0],j[1]+1):
                      a[k-1]=a[k-1]+j[2]
              return (max(a))
          
        • + 1 comment

          these solutions give runtime error

          • + 1 comment

            yup for 7 testcase its showing time out what should I do??

            • + 0 comments

              hi,

              I am sure this comment will definately help you to solve your problem.

              https://www.hackerrank.com/challenges/crush/forum/comments/570284

        • + 0 comments

          okay its great but why you using if((y)<=len(list)):

        • + 0 comments

          Hi, I have an even simpler solution. But, I am still getting a run time error. Can anyone please help me with this. Here is my code in Python 3:

          def arrayManipulation(arr, query): a, b, k = query[0], query[1], query[2] arr[a - 1 : b] = [arr[i] + k for i in range(a - 1, b)] return arr

        • + 0 comments

          tq

        • + 0 comments

          The condition check

          if((y)<=len(list)) will always return true since len(list)==n+1 to start with and hence redundant. This condition makes more sense if len(list)==n. This code will work perfectly fine though, just pointing out in case someone is confused regarding why this condition check is there.

        • + 0 comments

          I replaced this part of your code :

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

          by this:

          max=list1[0] for j in range(1,n): list1[j]=list1[j]+list1[j-1] if max

          here list1 is prefix sum array why did my code failed few test cases? here's my entire code : def arrayManipulation(n, queries): list1=[0]*(n+1)

          for i in range(len(queries)):
              list1[queries[i][0]-1]+=queries[i][2]
              list1[queries[i][1]]+=-queries[i][2]
          """prefix sum"""
          max=list1[0]
          for j in range(1,n):
              list1[j]=list1[j]+list1[j-1]
              if max<list1[j]:
                  max=list1[j]
          return(max)
          
          
          
          
          
          
              if max<list1[j]:
                  max=list1[j]
          
      • + 3 comments

        I still have some doubt if anyone could explain it. I understand that it is making use of difference array to keep track of the difference between items rather than updating every item.

        However as I understand, size of difference array is one less than total items in the actual array.

        So as per the demo program given,

              	  ARR						DIFF
        (5,3)  0    0    0    0    0		0    0     0    0
        (1,2)  100  100  0    0    0		0    -100  0    0
        (2,5)  100  200  100  100  100		100  -100  0    0
        (3,4)  100  200  200  200  100		100  0     0    -100
        

        However the logic used seems to be a variant of difference array that I am not able to understand. It would be great if someone could help me connect the dots from this difference array to the actual working solution of this problem. Thanks.

        • + 1 comment

          Hello, I don't really get your DIFF representation, but here is the deal:

          you need to keep in mind that at the end of queries to get the real value of i we need to sum the values of A[0]->A[i].

          for a query (l, r, x) if we add x to A[l] then we're sure later for every k in [l, r] sums(0->k) will include x.

          the problem is that every k > r will also include that x, therefore we'll decrement l[r+1] by x.

          Now the sum through 0 -> k will include x only if k >= l and will exclude it only if k > r which is equivalent to:

          sum(0->k) will consider x only if k is in [l, r]

        • + 3 comments

          I think the DIFF matrix should be:

          0    0    0    0    0
          100  0    0    -100 0
          0    100  0    0    0
          0    0    100  0    -100
          

          then x is 100+100+100-100-100 = 200

          still don't quite get it though

          • + 1 comment

            I think the Diff should like this

              0   0   0   0   0 
              100  0  -100  0    0  <--- 1 2 100, 3rd col is 100 less than 2nd col 
              100  100 -100 0    0  <--- 2 5 100, 2nd col is 100 more than 1st col
              100  100  0  0  -100   <--- 3 4 100, now 3rd is equal to 2nd, and 5th is 100 less than 4th col
            

            so finally, 1st col is always the real value, and others are accumlated of previous values and it self. so actual values are 100 200 200 200 100, max is 200

            • + 0 comments

              Thanks this helps me to understand how it works.

          • + 2 comments

            @julie_larson
            100+100+100-100-100 = 100 still not 200 I've been banging my head still not able to understand this solution.

            • + 0 comments

              The final diff array should be like this:

              100 100 0 0 -100 (straight foward from the code)

              So when you iterate over it to get the accumalated sum you'll get this:

              iteration		value of x	accumulated sum
              0			0		0
              1			100		100
              2			100		200	
              3			0		200
              4			0		200
              5			-100		100
              

              The maximum value of the accumulated sum is 200.

            • + 0 comments

              They're always checking the sum against the count, so when the sum is less than the count (which is the greatest sum so far) the count doesn't update.

        • + 0 comments

          As i have understood (5 , 3) 0 0 0 0 0 (1 , 2) 100 100 0 0 0 -> first and second places i.e a=1,b=2 , k=100, now a+k = 0+100 = 100, b+K = 0+100 = 100. (2 , 5) now from 2 to 5 i.e 2,3,4,5 are added with K i.e 100. already 2=100 now 2 becomes 100+100 =200, simialrly 3 = 0+100=100,4=0+100=100,5=0+100=100. (3 , 4) now 3 and 4 are added with 100. ie 3 value is 100 it becomes 100+100=200, 4 becomes 100+100=200.

          among these 200 is max value.

      • + 4 comments

        instead of writing long int *a=long int[n+1] if I write long int a[n+1]; It shows segmentation fault after test case 7. why? Explain please.

        • + 0 comments

          yes ,the same with you, i am confused

        • + 0 comments

          you aren't allocating space for a that way. He uses new to create an array on the heap. You are trying to declare it on the stack, but you can't do that with a dynamic value like 'n'

        • + 2 comments

          As per my knowledge, u can create an array to size upto 10^6 in stack and for size above it we need to create in heap so we do it dynamically. https://discuss.codechef.com/questions/28604/maximum-size-of-an-array refer this

          • + 0 comments

            Thanks @ami3443

          • + 1 comment

            for me the best explanation for the dynamic allocation was:-here!

            • + 0 comments

              Nice explanation.

        • + 0 comments

          If you have a problem understanding dynamic memory then make use of vector . It allocates memory dynamically wherein the user doesn't have to deal with pointers .

          vector arr(n); declares an array of long int of length n.

    • + 0 comments

      Thanks for explaining the logic behind this.

    • + 1 comment

      Here ,I add all the positive values of the difference array to get the maximum element . But , the answer comes out to be wrong for all the test cases except sample one ...

      image

      • + 0 comments

        Use long int in place of int.

    • + 1 comment

      what do u mean by previous element? is it a[p-1]for a[p] or the previous state of a[p] before the current updation operation? difference is betweentwo succesive elements or in the same element before and after one query is executed?

      • + 0 comments

        It is a[p-1] for a[p] ie. the difference between two successive elements.

        Well ,now ,i understood my mistake . I was just adding the positive differences. But the problem requires maximum element in an array , so there must be a comparison while adding the differences.

        Well thanks!

    • + 0 comments

      wonderful explaination...Thanks a lot

    • + 0 comments

      Hi gabriel

    • + 0 comments

      how is element at b+1 the previous element?

    • + 0 comments

      Thank you ! Good to see this better way to store the difference only , so array size = n+1 only !

    • + 0 comments

      Hi,

      Most of the peope solved this problem but time complexity of solution is O(n*m) (due to two nested for loops)which can not be used to solve this problem for given time constraint, so you need better approach which beats O(n*m)

      I have created a video tutorial for all and uploaded the same on youtube with complete explanation along with code complexity analysis.

      Here is the video tutorial for my solution O(n+m) complexity passed all test cases.

      https://youtu.be/hDhf04AJIRs

      Would really appreciate your feedback like, dislike , comment etc. on my video.