human
Write me a code to count of Arrays of size N having absolute difference between adjacent elements at most 1 and the other steps required given the following:
Count of Arrays of size N having absolute difference between adjacent elements at most 1 | Function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1.
Stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last element as j.
Case where 1 st array element is missing.
All integers in range [ 1 , M ] are reachable.
Only reachable integer is arr [ 0 ].
Iterate through all values of i.
If arr [ i ] is not missing.
Only valid value of j is arr [ i ].
If arr [ i ] is missing.
Iterate through all possible values of j in range [ 1 , M ].
Stores the count of valid arrays.
Calculate the total count of valid arrays.
Return answer.
Driver Code.
Function Call"
Solution in Python:
assistant
#Here is code to count of Arrays of size N having absolute difference between adjacent elements at most 1 and the other steps required.
 def countArray ( arr , N , M ) :
	dp = [ [ 0 for i in range ( M + 2 ) ] for j in range ( N ) ]
	if ( arr [ 0 ] == - 1 ) :
		for j in range ( 1 , M + 1 , 1 ) :
			dp [ 0 ] [ j ] = 1
	else :
		dp [ 0 ] [ arr [ 0 ] ] = 1
	for i in range ( 1 , N , 1 ) :
		if ( arr [ i ] != - 1 ) :
			j = arr [ i ]
			dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ]
		if ( arr [ i ] == - 1 ) :
			for j in range ( 1 , M + 1 , 1 ) :
				dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ]
	arrCount = 0
	for j in range ( 1 , M + 1 , 1 ) :
		arrCount += dp [ N - 1 ] [ j ]
	return arrCount
if __name__ == ' _ _ main _ _ ' :
	arr = [ 4 , - 1 , 2 , 1 , - 1 , - 1 ]
	N = len ( arr )
	M = 10
	print ( countArray ( arr , N , M ) )