LeetCode 3187: Peaks in Array Solution
Master LeetCode problem 3187 (Peaks in Array), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3187. Peaks in Array
Problem Explanation
Explanation:
To solve this problem, we can iterate over the array nums to count the number of peaks initially. Then, for each query of type 1, we update the value of the specified index and check if it affects the peak count. We can maintain a boolean array isPeak to keep track of whether an element is a peak or not.
For each query of type 1, we update the value at the specified index and check if it becomes a peak or not. If the value increases and becomes a peak, we increment the peak count. If the value decreases and is no longer a peak, we decrement the peak count.
Time Complexity:
The time complexity of this approach is O(N + Q), where N is the number of elements in the nums array and Q is the number of queries.
Space Complexity:
The space complexity is O(N) to store the isPeak array.
:
Solution Code
class Solution {
public int[] processQueries(int[] nums, int[][] queries) {
int n = nums.length;
int[] result = new int[queries.length];
boolean[] isPeak = new boolean[n];
int peakCount = 0;
for (int i = 1; i < n - 1; i++) {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
isPeak[i] = true;
peakCount++;
}
}
for (int i = 0; i < queries.length; i++) {
if (queries[i][0] == 1) {
int left = queries[i][1];
int right = queries[i][2];
for (int j = left + 1; j < right; j++) {
if (!isPeak[j] && nums[j] > nums[j - 1] && nums[j] > nums[j + 1]) {
isPeak[j] = true;
peakCount++;
} else if (isPeak[j] && (nums[j] <= nums[j - 1] || nums[j] <= nums[j + 1])) {
isPeak[j] = false;
peakCount--;
}
}
result[i] = peakCount;
} else {
int index = queries[i][1];
int newVal = queries[i][2];
if (isPeak[index] && (newVal <= nums[index - 1] || newVal <= nums[index + 1])) {
isPeak[index] = false;
peakCount--;
} else if (!isPeak[index] && newVal > nums[index - 1] && newVal > nums[index + 1]) {
isPeak[index] = true;
peakCount++;
}
nums[index] = newVal;
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3187 (Peaks in Array)?
This page provides optimized solutions for LeetCode problem 3187 (Peaks in Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3187 (Peaks in Array)?
The time complexity for LeetCode 3187 (Peaks in Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3187 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3187 in Java, C++, or Python.