Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Difference Array | Range update query in O

# Python3 code to demonstrate Difference Array
 
# Creates a diff array D[] for A[] and returns
# it after filling initial values.
def initializeDiffArray( A):
    n = len(A)
 
    # We use one extra space because
    # update(l, r, x) updates D[r+1]
    D = [0 for i in range(0 , n + 1)]
 
    D[0] = A[0]; D[n] = 0
     
    for i in range(1, n ):
        D[i] = A[i] - A[i - 1]
    return D
 
 
# Does range update
def update(D, l, r, x):
 
    D[l] += x
    D[r + 1] -= x
 
 
# Prints updated Array
def printArray(A, D):
 
    for i in range(0 , len(A)):
        if (i == 0):
            A[i] = D[i]
 
        # Note that A[0] or D[0] decides
        # values of rest of the elements.
        else:
            A[i] = D[i] + A[i - 1]
 
        print(A[i], end = " ")
     
    print ("")
 
 
# Driver Code
A = [ 10, 5, 20, 40 ]
 
# Create and fill difference Array
D = initializeDiffArray(A)
 
# After below update(l, r, x), the
# elements should become 20, 15, 20, 40
update(D, 0, 1, 10)
printArray(A, D)
 
# After below updates, the
# array should become 30, 35, 70, 60
update(D, 1, 3, 20)
update(D, 2, 2, 30)
printArray(A, D)
 
# This code is contributed by Gitanjali.
Comment

PREVIOUS NEXT
Code Example
Cpp :: go to particular place in vector using iterator 
Cpp :: cpprestsdk header 
Cpp :: c++ correct upto 3 decimal places 
Cpp :: move letter position using c++ with input 
Cpp :: distinct numbers cses 
Cpp :: deliberation meaning 
Cpp :: c++ freecodecamp course 10 hours youtube 
Cpp :: enqueue function with linked list implementation in c++ 
Cpp :: empty 2d array as a member of a class class c++ 
Cpp :: haxelib install cpp 
Cpp :: sort c++ stl 
Cpp :: return multiple objects from a function C++ using references 
Cpp :: create a table using pointers in C++ 
Cpp :: last element of a set in c++ 
Cpp :: how to print std::string 
Cpp :: std::hash 
Cpp :: sort array using stl 
Cpp :: C++ with SVD 
Cpp :: fibonacci search algorithm c++ 
Cpp :: convert "c++ to c" code online 
Cpp :: unreal ensureMsgf example 
Cpp :: c++ language 
Cpp :: What will be the values of variables p, q and i at the end of following loop? int p = 5; int q = 18; for(int i=1;i<5;i++) p++; --q; 
Cpp :: flutter websocket auto reconnect 
Cpp :: how to input a file path in c++ 
Cpp :: c++ to c converter 
Cpp :: convert ros time to double 
Cpp :: c++ cout int 
Cpp :: how to append two vectors in c++ 
Cpp :: constructor overloading in c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =