Update SinglePeakFinder.java

This commit is contained in:
Imran Alam 2024-03-01 13:18:05 +05:30 committed by GitHub
parent 32873a43b1
commit 1c2c142003
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 16 additions and 11 deletions

View File

@ -1,25 +1,30 @@
package com.baeldung.peakelements; package com.baeldung.peakelements;
public class SinglePeakFinder { import java.util.OptionalInt;
public static int findSinglePeak(int[] arr) { public class SinglePeakFinder {
public static OptionalInt findSinglePeak(int[] arr) {
int n = arr.length; int n = arr.length;
if (n < 2) {
return n == 0 ? OptionalInt.empty() : OptionalInt.of(arr[0]);
}
if (arr[0] >= arr[1]) {
return OptionalInt.of(arr[0]);
}
for (int i = 1; i < n - 1; i++) { for (int i = 1; i < n - 1; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) { if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) {
return arr[i]; return OptionalInt.of(arr[i]);
} }
} }
if (arr[0] > arr[1]) { if (arr[n - 1] >= arr[n - 2]) {
return arr[0]; return OptionalInt.of(arr[n - 1]);
} }
if (arr[n - 1] > arr[n - 2]) { return OptionalInt.empty();
return arr[n - 1];
}
return -1;
} }
} }