Problem:
Score : 700 points

Problem Statement

Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1).

Now, he will perform the following operation exactly once:

Choose K consecutive elements in P and sort them in ascending order.

Find the number of permutations that can be produced as P after the operation.

Constraints

2 \leq N \leq 200000

2 \leq K \leq N

0 \leq P_i \leq N-1

P_0,P_1,\cdots,P_{N-1} are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_0 P_1 \cdots P_{N-1}

Output

Print the number of permutations that can be produced as P after the operation.

Sample Input 1

5 3
0 2 1 4 3

Sample Output 1

2

Two permutations can be produced as P after the operation: (0,1,2,4,3) and (0,2,1,3,4).

Sample Input 2

4 4
0 1 2 3

Sample Output 2

1

Sample Input 3

10 4
2 0 1 3 7 5 4 6 8 9

Sample Output 3

6

Solution in Rust (1.15.1) (judge verdict: Time Limit Exceeded)

use std::cmp::{max, min};
use std::io::{stdin, Read};
use std::str::FromStr;

// https://qiita.com/tubo28/items/e6076e9040da57368845
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

#[allow(dead_code)]
fn main() {
    let n = read::<usize>();
    let k = read::<usize>();
    let pp = (0..n).map(|_| read::<usize>()).collect::<Vec<_>>();
    let end = n - k + 1;
    let mut prev_min = usize::max_value();
    let mut prev_max = 0;

    let mut first_is_sorted = true;

    for i in 0..k {
        prev_min = min(prev_min, pp[i]);
        prev_max = max(prev_max, pp[i]);
        if i > 0 && pp[i - 1] > pp[i] {
            first_is_sorted = false
        }
    }

    let mut sorted_count = 0;
    let mut ans = 1;

    for start in 1..end {
        // duplicate with prev
        let is_duplicated = prev_max <= pp[start + k - 1] && prev_min == pp[start - 1];

        let mut need_swap = false;
        prev_min = pp[start];
        prev_max = pp[start];

        for i in 1..k {
            let index = start + i;
            prev_min = min(prev_min, pp[index]);
            prev_max = max(prev_max, pp[index]);

            if pp[index - 1] > pp[index] {
                need_swap = true
            }
        }

        if is_duplicated {
            continue; // duplicate with prev
        } else if !need_swap {
            sorted_count += 1;
            continue; // duplicate with prev (sorted)
        } else {
            ans += 1
        }
    }

    if !first_is_sorted && sorted_count > 0 {
        ans += 1
    }

    println!("{}", ans);
}