It is necessary to determine the maximum number of consecutive positive elements, not interrupted by either zeros or negative numbers. For example, in this case it is necessary to output the resulting array with the elements {6, 3, 5, 7, 7, 1} And how to make an outer loop so that it would iterate over all the sequence of numbers between the following negative numbers?

  nt[] arr = { -1, 3, 4, 5, 9, -7, 6, 3, 5, 7, 7, 1, -9 }; int startIndex = 0; int endIndex = 0; for (int i = 0; i < arr.length; i++) { for (int k = 0; k < arr.length; k++) { if (arr[k] > 0) { startIndex = k; System.out.println(startIndex); break; } } for (int y = startIndex; y < arr.length; y++) { if (arr[y] < 0) { endIndex = y; System.out.println(endIndex); break; } } int length = endIndex - startIndex; System.out.println(length); } 
  • What do you want to achieve in arraycopy in general, if your array is now 0 3 4 5 9 0 6 3 5 7 7 1 0 and start will be equal to 1 ...... what can you understand from it? You have the wrong logic already - Alexey Shimansky
  • I can not understand how to find the longest gap and how to find the beginning and the end. What should be the logic, please tell me? - Nevada
  • 2
    look for the non-negative and move to the negative or the end of the array, compare the length with the maximum stored, choose more, now in a circle - splash58
  • and how to move to the negative? @ splash58 - Nevada 9:14 pm
  • index of the array increase until the element is positive - splash58

1 answer 1

  nt[] arr = { -1, 3, 4, 5, 9, -7, 6, 3, 5, 7, 7, 1, -9 }; int indexStartBest = -1; int lengthBest = 0; int indexStartCurrent = -1; int lengthCurrent = 0; for (int i = 0; i<arr.length; i++) { if(arr[i] > 0) { if(lengthCurrent == 0) indexStartCurrent = i; lengthCurrent++; } if(arr[i] <= 0 || i == arr.length-1) { if(lengthCurrent && lengthCurrent > lengthBest) { indexStartBest = indexStartCurrent; lengthBest = lengthCurrent; } lengthCurrent = 0; } } System.out.println(lengthBest);