Problem Description
Given an array of integers nums and a positive integer k, we need to compute the "power" of every contiguous subarray of size k. The power of a subarray is defined as the maximum element of the subarray if its elements are consecutive numbers sorted in ascending order; otherwise, the power is -1. Return an array where each element is the power of the corresponding subarray.
Key Insights
- Use a sliding window of size k to traverse the array.
- For each subarray, check if the elements are strictly increasing and consecutive.
- To do this, iterate over the subarray and ensure that for every adjacent pair, the difference is exactly 1.
- If the subarray meets the criteria, its power is the last (maximum) element; otherwise, the power is -1.
Space and Time Complexity
Time Complexity: O(n * k), where n is the number of elements in nums. For each of the (n - k + 1) windows, we perform k-1 comparisons. Space Complexity: O(n - k + 1) for the output array, and O(1) extra space is used within each window.
Solution
We use a simple sliding window approach to iterate through all contiguous subarrays of size k. For each window, we check if the subarray is sorted in ascending order with consecutive values. The check is performed by comparing adjacent elements to see if the difference is exactly 1. If the condition is satisfied, we record the last element (the maximum in the window) as the power of that subarray; otherwise, we record -1.