• + 0 comments

    If your code is timing out. Use prefix array method, I used https://akd3257.medium.com/understanding-the-concept-of-prefix-sum-array-70fb333169a4 to understand the concept.

    Solution in Ruby:

    def arrayManipulation(n, queries)
        prefix_sum_array = Array.new(n, 0)
        queries.each do |query|
          prefix_sum_array[query[0] - 1] += query[2]
          next if query[1] >= prefix_sum_array.length
    
          prefix_sum_array[query[1]] -= query[2]
        end
        max_sum = 0
        prefix_sum_array.each_with_index do |_sum, index|
          next if index == 0
          prefix_sum_array[index] += prefix_sum_array[index - 1]
          max_sum = prefix_sum_array[index] if prefix_sum_array[index] > max_sum
        end
        max_sum
    end