Queries to find maximum sum contiguous subarrays of given length in a rotating array | Function to calculate the maximum sum of length k ; Calculating the max sum for the first k elements ; Find subarray with maximum sum ; Update the sum ; Return maximum sum ; Function to calculate gcd of the two numbers n1 and n2 ; Base Case ; Recursively find the GCD ; Function to rotate the array by Y ; For handling k >= N ; Dividing the array into number of sets ; Rotate the array by Y ; Update arr [ j ] ; Return the rotated array ; Function that performs the queries on the given array ; Traverse each query ; If query of type X = 1 ; Print var the array ; If query of type X = 2 ; Given array arr ; Given Queries ; Function Call
function MaxSum ( arr , n , k ) { var i , max_sum = 0 , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } max_sum = sum ; while ( i < n ) { sum = sum - arr [ i - k ] + arr [ i ] ; if ( max_sum < sum ) { max_sum = sum ; } i ++ ; } return max_sum ; } function gcd ( n1 , n2 ) { if ( n2 == 0 ) { return n1 ; } else { return gcd ( n2 , n1 % n2 ) ; } } function RotateArr ( arr , n , d ) { var i = 0 , j = 0 ; d = d % n ; var no_of_sets = gcd ( d , n ) ; for ( i = 0 ; i < no_of_sets ; i ++ ) { var temp = arr [ i ] ; j = i ; while ( true ) { var k = j + d ; if ( k >= n ) k = k - n ; if ( k == i ) break ; arr [ j ] = arr [ k ] ; j = k ; } arr [ j ] = temp ; } return arr ; } function performQuery ( arr , Q , q ) { var N = arr . length ; for ( i = 0 ; i < q ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { arr = RotateArr ( arr , N , Q [ i ] [ 1 ] ) ; for ( var t = 0 ; t < arr . length ; t ++ ) { document . write ( arr [ t ] + " " ) ; } document . write ( " " ) ; } else { document . write ( MaxSum ( arr , N , Q [ i ] [ 1 ] ) + " " ) ; } } } var arr = [ 1 , 2 , 3 , 4 , 5 ] ; var q = 5 ; var Q = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 1 ] , [ 2 , 4 ] ] ; performQuery ( arr , Q , q ) ;