8 条回复
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = sc.nextInt(); } int left = -1, right = -1; int lastLeft = -1, lastRight = -1; for(int i = 0; i < n-1; i++){ if(lastLeft == -1){ if(arr[i] < arr[i+1]){ lastLeft = i; } }else{ if(arr[i] < arr[i+1] && arr[i] < arr[i-1]){ lastRight = i; if(lastRight - lastLeft > right - left){ left = lastLeft; right = lastRight; } lastLeft = lastRight; } } } if(arr[n-1] < arr[n-2]){ lastRight = n-1; if(lastLeft!=-1 && lastRight - lastLeft > right - left){ left = lastLeft; right = lastRight; } } System.out.println(left+" "+right); } }
import java.util.*; public class Main { public static void main(String[] args) { /*输入*/ int n; Scanner sc = new Scanner(System.in); n=sc.nextInt(); int [] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } /*定义返回区间和最大区间值*/ int max = 0; int [] ret = new int[2]; ret[0] = -1; ret[1] = -1; /*求最大区间*/ int temp1=-1,temp2=-1; int i=1; if(arr[1]<arr[0]){//上升区间为0 while(i<n&&arr[i]<arr[i-1]){ i++; } //System.out.printf("hello"); } //System.out.printf("jinru%d\n",i); temp1 = i-1;//当前最低点 int count = 0; while(i<n-1){ if(arr[i-1]>arr[i]){ if(arr[i+1]>arr[i]){//找到最低点,保存前一个符合条件区间 temp2=i; if(count>max){ max = count; ret[0]=temp1; ret[1] = temp2; //System.out.printf("shuchu%d %d %d\n",max,ret[0],ret[1]); } temp1 = i; count = 0;//初始化新区间 } else{ count++; temp2 = i; } } else{ if(arr[i]>arr[i+1]){ count++; temp2 = i; } else{ count++; } } i++; } if(arr[n-1]<arr[n-2]){ count++; if(count>max){ ret[0]=temp1; ret[1] = n-1; } } System.out.printf("%d %d",ret[0],ret[1]); sc.close(); } }
添加回复