Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. public int solution(int[] A) {
  2. int maxSize = 0;
  3. // initialize the list where to put every beginning slice of maximum
  4. // size
  5. List<Integer> beginSlice = new ArrayList<Integer>();
  6. for (int i = 0; i < A.length; i++) {
  7. int startSlice = i;
  8. int j = i + 1;
  9. // initialize current max
  10. int currMax = 0;
  11. // compare each i with its consecutive
  12. // and stop when A[i+1> < A[i] or A.length is reached
  13. while (j < A.length && A[j] > A[i]) {
  14. // update current maximum size slice
  15. currMax = j - startSlice + 1;
  16. i++;
  17. j = i + 1;
  18. }
  19. // compare current maximum size slice with the maximum size
  20. if (currMax > maxSize) {
  21. // remove all old beginning slices of previous maximum size
  22. if (!beginSlice.isEmpty())
  23. beginSlice.removeAll(beginSlice);
  24. // add beginning slice to the list
  25. beginSlice.add(startSlice);
  26. // update maximum size
  27. maxSize = currMax;
  28. } else if (currMax == maxSize) {
  29. beginSlice.add(startSlice);
  30. }
  31. }
  32. // return any beginning slice of A of maximum size
  33. Random randomizer = new Random();
  34. Integer randomBSlice = beginSlice.get(randomizer.nextInt(beginSlice.size()));
  35. return randomBSlice.intValue();
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement