diff --git a/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java index 7b8cd76075..f7b7cfc72b 100644 --- a/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java +++ b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java @@ -1,25 +1,30 @@ 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; + 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++) { - if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) { - return arr[i]; + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return OptionalInt.of(arr[i]); } } - if (arr[0] > arr[1]) { - return arr[0]; + if (arr[n - 1] >= arr[n - 2]) { + return OptionalInt.of(arr[n - 1]); } - if (arr[n - 1] > arr[n - 2]) { - return arr[n - 1]; - } - - return -1; + return OptionalInt.empty(); } }