Advertisement
remote87

almostIncreasingSequence

Jan 30th, 2021
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. // Return true if it is possible to remove one element from the array in order
  2.     // to get a strictly increasing sequence, otherwise return false.
  3.     // Sequence containing only one element is also considered to be strictly increasing.
  4.     if (sequence.length <= 2) {
  5.       return true;
  6.     }
  7.     int count = 0;
  8.     // 1, 2, 3, 4, 99, 5, 6
  9.     for (int i = 0; i < sequence.length - 1; i++) {
  10.       if (sequence[i + 1] <= sequence[i]) {
  11.         // remove one element from the array
  12.         count++;
  13.         if (i==0) {
  14.           // directly skip, if it is the first element in the array
  15.           // Example: {10, 1, 2, 3, 4, 5}
  16.           continue;
  17.         }
  18.         boolean hasPrevious = i - 1 >= 0;
  19.         boolean hasNext = i + 1 < sequence.length;
  20.         // Example: { 1, 2, 3, 4, 99, 5, 6 }
  21.         if (hasPrevious && hasNext && sequence[i+1] > sequence[i-1]) {
  22.           continue;
  23.         }
  24.         // Example: 40, 50, 60, 10, 20, 30
  25.         hasNext = i + 2 < sequence.length;
  26.         if (hasNext && sequence[i + 2] <= sequence[i]) {
  27.           return false;
  28.         }
  29.       }
  30.     }
  31.     return count <= 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement