problem : 581 Shortest Unsorted Continuous Subarray
Anonymous User
227

problem : 581
Shortest Unsorted Continuous Subarray
what is wrong with this code?
It shows test case fails but why?
Test case failed : {2,1}
But the above test case gives me the right result.

class Solution {

static Scanner scan =   new Scanner(System.in);
static int min_pos = Integer.MIN_VALUE;
static int max_pos = Integer.MAX_VALUE;
static int j , x;

public static int findUnsortedSubarray(int[] nums) {
	ArrayList<Integer> list = new ArrayList<>(nums.length);
	for(int i: nums){
	list.add(i);
	}
	System.out.println("list before : " + list);
	int size = list.size();
	
	int min = Integer.MIN_VALUE;
	int max = Integer.MAX_VALUE;
	j = list.size();
	int jj = list.size();
    for(int i=0 ; i<jj ; i++) {
		if (size == 0) {break;}
    	
    	
		  if(list.get(i) < list.get(j-1) && list.get(j-1)<max && min<list.get(i))
		  { 
			  
			  min = list.get(i);
			  max = list.get(j-1);
			  min_pos = i;
			 max_pos = j-1;
			  j = j-1;

		  }	
		  
		 
		 
   }
	  System.out.println("min " + min_pos);
	  System.out.println("max " + max_pos);
	  
    	if (jj%2 == 0  && jj-1 != 0) {
    		
    		 x =  Math.abs(((jj-min_pos-1)-(jj-max_pos-1))-1);
    	}
    	
    	else
    	{
    		if (jj-1 == 0) {return 0;}
    		 x = Math.abs(((jj-min_pos-1)-(jj-max_pos-1))+1);
    	}
    	
    	return x;
	  }

	 



public static void main(String args[]){
	/*
	 * System.out.println("taking entry from user for array list"); do {
	 * System.out.println("current list is :" + list);
	 * System.out.println("add more ? 'y' / 'n' ");
	 * if(scan.next().equalsIgnoreCase("y")) { System.out.print("Enter : ");
	 * list.add(scan.nextInt()); }else break; } while(true);
	 */
	//int arr1[] =new int[] {2,6,4,8,10,9,15};
	//int arr1[] =new int[] {1,2,3,4};
	int arr1[] =new int[] {2,1};
    int y = findUnsortedSubarray(arr1);
    System.out.println("length of shortest unsorted array is: " + x );
   
}

}

Comments (0)