• + 3 comments

    Javascript. does anyone know how I would make this faster??

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

      Lets investigate using LLM

    • + 0 comments

      Nope...I gave up....Hackerrank does not explain why it fails even though the run time is less than 10s

    • + 1 comment

      You're using N^2 TC for this while this can be done in O(n) using prefix sum method.

      public static long arrayManipulation(int n, List<List<Integer>> queries) {
      
          long arr[] = new long[n];
          for (List<Integer> query : queries) {
              arr[query.get(0)-1] += query.get(2);
              if (query.get(1)<n) {
                  arr[query.get(1)] -= query.get(2);
              }
          }
      
          long res =Long.MIN_VALUE;
          long sum = 0;
          for (long x : arr) {
              sum+=x;
              res=Math.max(res, sum);
          }
          return res;
      
      }
      
      • + 1 comment

        you need to initialize n + 1 length of array instead, otherwise it will throw index out of bound exception

        • + 0 comments

          nope. i am already handling that in th if condition. no need to create that exyra index array.