Problem 2. Why Did the Cow Cross the Road II Return to Problem List code example

Example: Problem 2. Why Did the Cow Cross the Road II Return to Problem List

//Click the Source(Below) To View The Problem
import java.util.*;
import java.io.*;
public class maxcross {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(new File("maxcross.in"));
        int n = sc.nextInt(); int k = sc.nextInt(); int b = sc.nextInt();
        int[] list = new int[n+1];
        int broken = 0;
        for (int i = 0; i < b; i++) list[sc.nextInt()] = 1;
        for (int i = 1; i <= n; i++){
            if (list[i] == 1)
                broken++;
            list[i] = broken;
        }
        int answer = -1;
        // System.out.println(Arrays.toString(list));
        for (int i = n; i >= k; i--) {
            int thisI = list[i] - list[i-k];
            if (answer == -1 || answer > thisI) {
               answer = thisI; 
            } 
        }
        PrintWriter out = new PrintWriter(new File("maxcross.out"));
        out.print(answer);
        out.close();
    } 
}

Tags:

Java Example