Minimum replacements in given Array to remove all strictly peak elements
Given an array arr[] of length N, the task is to find the minimum number of replacements required to remove all peak elements of the array.
Note: An element is said to be a peak element if it is strictly greater than both of its neighbours. Corner elements cannot be peak elements, because they have only one neighbour.
Examples:
Input: arr = { 3, 2, 3}
Output: operations = 0
arr = { 3, 2, 3}
Explaination : There is no peak element in arrayInput: arr = { 2, 2, 3, 1, 3, 1 3, 1, 3}
Output: operations = 2
arr = {2, 2, 3, 3, 3, 1, 3, 3, 3 }
Explaination: Thereare three peak elements at arr[2], arr[4] and arr[6].
Replace arr[3] with arr[4] and arr[7] with arr[8]
Approach: The idea to solve this problem is to convert the valley elements to adjacent strictly peak elements. This can be done as shown below:
If an element arr[i] is a peak element, replace arr[i +1] with max of arr[i+2] and arr[ i ]. This will eliminate the chances of arr[ i ] and arr[i+2] of becoming peak elements at the same time.
If i+2 exceeds the array bound then replace arr[i] with max of arr[i-1] and arr[i+1] as this will eliminate chance of arr[i] being a peak.
Follow the steps mentioned below to solve the problem:
- Iterate from the starting of the array.
- Check if the ith element is peak or not:
- If it is a peak increase the replacement count by 1 and change the as per the conditions mentioned above.
- Otherwise, skip this element and continue iteration.
- Return the final count and the final array.
Below is the implementation of the above approach.
Java
// Java code to implement the approach import java.io.*; class GFG { // Function to find the count // of replacements and the final array public static void solution(int[] arr, int n) { // Count of operations int cnt = 0; for (int i = 1; i < n - 1; i++) { // Check if it is peak or not if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) { cnt++; if (i < n - 2) arr[i + 1] = Math.max(arr[i], arr[i + 2]); else arr[i] = Math.max(arr[i + 1], arr[i - 1]); } } System.out.println(cnt); for (int i : arr) System.out.print(i + " "); } // Driver Code public static void main(String[] args) { int N = 9; int arr[] = { 2, 2, 3, 1, 3, 1, 3, 1, 3 }; solution(arr, N); }} |
2 2 2 3 3 3 1 3 3 3
Time Complexity: O(N)
Auxiliary Space: O(1)

