Print modified array after multiple array range increment operations | structure to store the ( start , end ) index pair for each query ; function to increment values in the given range by a value d for multiple queries ; for each ( start , end ) index pair , perform the following operations on ' sum [ ] ' ; increment the value at index ' start ' by the given value ' d ' in ' sum [ ] ' ; if the index ' ( end + 1 ) ' exists then decrement the value at index ' ( end + 1 ) ' by the given value ' d ' in ' sum [ ] ' ; Now , perform the following operations : accumulate values in the ' sum [ ] ' array and then add them to the corresponding indexes in ' arr [ ] ' ; function to print the elements of the given array ; Driver code ; modifying the array for multiple queries
class query { constructor ( start , end ) { this . start = start ; this . end = end ; } } function incrementByD ( arr , q_arr , n , m , d ) { let sum = new Array ( n ) ; for ( let i = 0 ; i < sum . length ; i ++ ) { sum [ i ] = 0 ; } for ( let i = 0 ; i < m ; i ++ ) { sum [ q_arr [ i ] . start ] += d ; if ( ( q_arr [ i ] . end + 1 ) < n ) sum [ q_arr [ i ] . end + 1 ] -= d ; } arr [ 0 ] += sum [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { sum [ i ] += sum [ i - 1 ] ; arr [ i ] += sum [ i ] ; } } function printArray ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 3 , 5 , 4 , 8 , 6 , 1 ] ; let q_arr = new Array ( 5 ) ; q_arr [ 0 ] = new query ( 0 , 3 ) ; q_arr [ 1 ] = new query ( 4 , 5 ) ; q_arr [ 2 ] = new query ( 1 , 4 ) ; q_arr [ 3 ] = new query ( 0 , 1 ) ; q_arr [ 4 ] = new query ( 2 , 5 ) ; let n = arr . length ; let m = q_arr . length ; let d = 2 ; document . write ( " " ) ; printArray ( arr , n ) ; incrementByD ( arr , q_arr , n , m , d ) ; document . write ( " " ) ; printArray ( arr , n ) ;