Update PeakElementFinder.java

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

View File

@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class PeakElementFinder { public class PeakElementFinder {
public List<Integer> findPeakElement(int[] arr) { public List<Integer> findPeakElements(int[] arr) {
int n = arr.length; int n = arr.length;
List<Integer> peaks = new ArrayList<>(); List<Integer> peaks = new ArrayList<>();
@ -16,6 +16,7 @@ public class PeakElementFinder {
if (isPeak(arr, i, n)) { if (isPeak(arr, i, n)) {
peaks.add(i); peaks.add(i);
} }
while (i < n - 1 && arr[i] == arr[i + 1]) { while (i < n - 1 && arr[i] == arr[i + 1]) {
i++; i++;
} }
@ -25,14 +26,19 @@ public class PeakElementFinder {
} }
private boolean isPeak(int[] arr, int index, int n) { private boolean isPeak(int[] arr, int index, int n) {
if (index == 0) { if (index == 0) {
return n > 1 ? arr[index] >= arr[index + 1] : true; return n > 1 ? arr[index] >= arr[index + 1] : true;
} else if (index == n - 1) { } else if (index == n - 1) {
return arr[index] >= arr[index - 1]; return arr[index] >= arr[index - 1];
} } else if (arr[index] == arr[index + 1] && arr[index] > arr[index - 1]) {
int i = index;
while (i < n - 1 && arr[i] == arr[i + 1]) {
i++;
}
return i == n - 1 || arr[i] > arr[i + 1];
} else {
return arr[index] >= arr[index - 1] && arr[index] >= arr[index + 1]; return arr[index] >= arr[index - 1] && arr[index] >= arr[index + 1];
} }
}
} }