Import java.util.LinkedList;
Maximum minus number of sub arrays with minimum value less than or equal to num public class getallsubarray{//Get the number of sub arrays public static int getnum (Int[]arr,int num) {if (arr==null| |
arr.length==0) {return 0; ///double-end queue record sub-array maximum and minimum value LinkedList <Integer> qmin=new linkedlist<integer> (); Record minimum value LinkedList <Integer> qmax= new linkedlist<integer> ();
Record maximum int i=0;
int j=0;
int res=0; while (I<arr.length) {while (j<arr.length) {while (!qmin.isempty () &&arr[qmin.pee
Klast ()]>=arr[j]) {qmin.polllast (); } qmin.addlast (j); New minimum to join Qmin queue tail while (!qmax.isempty () &&arr[qmax.peeklast ()]<=arr[j]) {Qmax.polllas
T ();
Qmax.addlast (j);//new maximum join Qmax queue tail if (Arr[qmax.getfirst ()]-arr[qmin.getfirst ()]>num) {
Break
} j + +; } if (Qmin.peeklast ()==i) {Qmin.pollfirst ();
} if (Qmax.peekfirst () ==i) {Qmax.pollfirst (); } res+=j-i;
i++ the number of total sub arrays;
return res; //Get a random array of public static int [] Getaarry (int leng) {if (leng==0) {return nu
ll
int arr[]=new Int[leng];
for (int i=0;i<leng;i++) {arr[i]= (int) (Math.random () *10);
return arr; ///print obtained random array public static void Printaarry (Int[]arr) {if (arr!=null) {for (int i=0;i&
lt;arr.length;i++) {System.out.print (arr[i]+ "");
}} public static void Main (string[] args) {, int []arr=getaarry (2);
Printaarry (arr);
Gets the number of System.out.println ("") that satisfies the condition;
System.out.println ("Number of sub arrays:" +getnum (arr,3)); }
}