Problem:
You are given an array a with n integers. A subarray is any subset of consecutive elements from this array. Let us call a subarray good if its first element is greater than or equal to the last element.
For example, if the given array is (2,5,1,6,4,7), then (5,1,6) is a subarray, but it is not a good subarray because 5 is lesser than 6. But the subarray (5,1,6,4) is good, because 5≥4.
My code is totally wrong in both of the implementation loop and recursive can someone please tell me where it is wrong?
Code:
import java.util.Scanner;
/**
- @author Vikalp Jain
*/
public class LGOODSUB2 {
//GLOBAL VARIABLES
static int arrMaxLength = 1;
static int globalStart=0,globalEnd=0; //pointers to store the first appearances
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
while(testCase>0) {
//getting array
int length = sc.nextInt();
int[] arr = new int[length];
for(int i =0;i<length;i++) {
arr[i] = sc.nextInt();
}
int j=arr.length-1;
for(int i =0;i<j;i++) {
for(;j>i;j--) {
// System.out.print(“start: “+i+”== “+arr[i]+” ||end:”+j+"== “+arr[j]);
// System.out.print(“arr[i] >=arr[j] : “+(arr[i] >=arr[j])+”|| arrMaxLength>j-i+1:”+(arrMaxLength>j-i+1));
// System.out.println(”");
if(arr[i] >=arr[j] && arrMaxLength<j-i+1) {
arrMaxLength = j - i +1;
// System.out.println(arrMaxLength);
}
}
j = arr.length - 1;
}
System.out.println(arrMaxLength);
testCase–;
}
}
public static void recFindSubArray(int[] arr, int startP, int endP) {
//termination condition
if(endP<0 ||startP >=arr.length-1)
return;
if(startP>=endP ) {
arrMaxLength = 1; //enhancing to reduce the code in output
return;
}
//avoid unnecessary attempts
if((endP-startP+1)<= arrMaxLength )
return;
//Putting condition before the recursion to terminate unnecessary computation.
// System.out.println(“start: “+startP+” ||end:”+endP);
if(arr[startP] >=arr[endP]) {
arrMaxLength = endP - startP +1;
globalStart = startP;
globalEnd = endP;
}
recFindSubArray(arr, startP+1, endP);
recFindSubArray(arr, startP, endP-1);
//Not putting both because it may compute more in some cases.
}
}