fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // AMAZON OA -26th August
  13. Scanner sc = new Scanner(System.in);
  14. int n = sc.nextInt();
  15. int[] arr = new int[n];
  16. for(int i=0; i<n; i++){
  17. arr[i] = sc.nextInt();
  18. }
  19. int k = sc.nextInt();
  20. System.out.println(getMinimumCost(arr, k));
  21. }
  22. public static int getMinimumCost(int[] arr, int k){
  23. int ones = 0;
  24. int min =Integer.MAX_VALUE;
  25. int cost =0;
  26. int r =0, l=0;
  27. while(r<arr.length){
  28. if(arr[r] == 1){
  29. ones++;
  30. cost++;
  31. }
  32. if(r-l+1 == k){
  33. min = Math.min(min, cost);
  34. cost -=arr[l];
  35. l++;
  36. }
  37. r++;
  38. }
  39. return (min*(min+1)/2)+ones-min;
  40. }
  41. }
Success #stdin #stdout 0.19s 56584KB
stdin
5
1
1
1
0
1
4
stdout
7