Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created February 8, 2023 12:34
Show Gist options
  • Save ravichandrae/10f5dfc16d044a0d1eab8f8e23eb7fee to your computer and use it in GitHub Desktop.
Save ravichandrae/10f5dfc16d044a0d1eab8f8e23eb7fee to your computer and use it in GitHub Desktop.
Finding the maximum element in a unimodal array (elements increases to a maximum and decreases there after). Efficient algorithm which runs in O(log n) time.
public class Main {
public static void main(String[] args) {
System.out.println(maxElementInUnimodalArray(new int[]{1, 2, 5, 4, 3})); //Expected 5
System.out.println(maxElementInUnimodalArray(new int[]{1, 2, 3, 4, 5})); //Expected 5
System.out.println(maxElementInUnimodalArray(new int[]{5, 4, 3, 2, 1})); //Expected 5
System.out.println(maxElementInUnimodalArray(new int[]{6})); //Expected 6
}
private static int maxElementInUnimodalArray(int[] arr) {
if (arr == null || arr.length == 0) {
return -1;
}
int low = 0, high = arr.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if ((mid == 0 || arr[mid] > arr[mid - 1]) &&
(mid == arr.length - 1 || arr[mid] > arr[mid + 1])) {
break;
}
if (mid > 0 && arr[mid] < arr[mid - 1]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return arr[mid];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment