Playing with stacks
Difficulty: Hard

Our friend John has N consecutive lined up stacks Ai with height 1, 2, 3,..., N-1, N. John can do successive swaps among
these stacks and reach some permutations. 

A permutation is considered beautiful if it matches a pattern. A pattern is sequence of N-1 numbers Pi
where Pi = 0 if Ai < Ai+1, and Pi = 1 if Ai > Ai+1.

John is interested in how many permutations can be reached who starts with a stack of height K.

**Input specification**

The first line contains two numbers N (2<=N<=1000) and K(1<=K<=N). Next follow a line with N-1 numbers Pi(0<=P1<=1),
the description of the pattern.

**Output specification**

Output just one line with the numbers of permutations that can be reached and start with a stack of height K.

**Sample input**
<br>4 3
<br>1 0 1

**Sample output**
<br>2

**Hint:**
<br>3 1 4 2
<br>3 2 4 1

Input Format:

Output Format:

Sample Input:

Sample Output:

Python 3 starter code:


Reference solution (Python):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	
	static int N, K;
	static int P[];
	static int DP[][];
	static String cad[];
	static int MOD = (int) 1e9 + 7;
	
	public static void main(String[] args) throws IOException {
		InputStreamReader sr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(sr);
		
		cad = br.readLine().split(" ");
		
		N = Integer.parseInt(cad[0]);
		K = Integer.parseInt(cad[1]);
		
		P = new int[N];
		DP = new int[N+1][N+1];
		
		cad = br.readLine().split(" ");
		for(int i = 0;i<N-1;i++)
			P[i] = Integer.parseInt(cad[i]);
		
		DP[N-1][1] = 1;
		
		for(int i=N-2;i>=0;i--) {
			if(P[i] == 0) {
				for(int j = 1;j <= N - i;j++) {
					DP[i][j] = (DP[i][j] + (DP[i+1][N - i - 1] + MOD - DP[i+1][j-1]) % MOD ) % MOD;
					DP[i][j] = (DP[i][j] + DP[i][j-1]) % MOD;
				}
			} else {
				for(int j = 1;j <= N - i;j++) {
					DP[i][j] = (DP[i][j] + DP[i+1][j-1]) % MOD;
					DP[i][j] = (DP[i][j] + DP[i][j-1]) % MOD;
				}
			}
		}
	
		System.out.println((DP[0][K] + MOD -  DP[0][K-1]) % MOD);
	}
}