To solve this problem let's first try to solve the following problem : Given a good array, A of length N find the lexicographic order of this array let's create a binary number of length N where the i-th bit is 0 if Ai = 1 and 1 if Ai = Ai-1 + 1 then if we convert this binary number into decimal we will get the lexicographic order of this array.
using this convention we can now represent each good array as a binary number of length N. And now since K is less than 10^9 then we only care about the last 31 bits that's because if any of the other bits had a value of 1 the array will have a lexicographic order of more than 10^9 so we can discard all these elements.
now to calculate the answer: since the discarded elements will always have a value of one in any good array then each one of them will increase the answer by K. as for the last 31 elements, we can calculate the answer for them using recursive dynamic programming with memoization.
let Dp[i][j][s] be a pair of numbers, the first one is the sum of all good arrays if we consider the elements from i to n and the last zero bit was at position j and s is a bool representing whether there was a bit that is turned on in K but turned off in our array
and the second number is the number of all good arrays if we were in that same state, let's call them Dp1[i][j][s] and Dp2[i][j][s] respectively.
then we will have the following two transitions:
1- make the i-th bit a zero then we will go from state (i ,j ,s ) to state (i+1 ,i , 1 if s was already one or if this bit is turned on in K and 0 otherwise) 2- make the i-th bit a one then we will go from state (i ,j ,s ) to state (i+1 ,j , s) keep in mind that the second transition can only be done if s was one or if the i-th bit is turned on in K.
finaly Dp2[i][j][s] will be the sum of Dp2 for the states that we can reach and Dp1[i][j][s] will be the value of the i-th element (1 in the first transition and i-j+1 in the second transition) multiplied by Dp2 of the new state we reached.