Sponsored
Sponsored
Solve with full IDE support and test cases
We can solve this problem by checking all possible subarrays of size k explicitly. For each subarray, we check if it is sorted and if the elements are consecutive. If both conditions are met, we calculate the power as the maximum element of the subarray. Otherwise, the power is -1.
Time Complexity: O(n * k)
because we process each element of each subarray of size k.
Space Complexity: O(n-k+1)
for storing the results array.
1#include <iostream>
2#include <vector>
3
4bool isConsecutive(const std::vector<int>& nums, int start, int k) {
5 for (int i = 1; i < k; ++i) {
6 if (nums[start + i] != nums[start + i - 1] + 1) return false;
7 }
8 return true;
9}
10
11std::vector<int> findPowerOfSubarrays(const std::vector<int>& nums, int k) {
12 int n = nums.size();
13 std::vector<int> results(n - k + 1, -1);
14 for (int i = 0; i <= n - k; ++i) {
15 bool sortedAndConsecutive = true;
16 int maxElement = nums[i];
17 for (int j = 1; j < k; ++j) {
18 if (nums[i + j] < nums[i + j - 1] || nums[i + j] != nums[i + j - 1] + 1) {
19 sortedAndConsecutive = false;
20 break;
21 }
22 if (nums[i + j] > maxElement) maxElement = nums[i + j];
23 }
24 if (sortedAndConsecutive) results[i] = maxElement;
25 }
26 return results;
27}
28
29int main() {
30 std::vector<int> nums = {1, 2, 3, 4, 3, 2, 5};
31 int k = 3;
32 std::vector<int> results = findPowerOfSubarrays(nums, k);
33 for (int result : results) {
34 std::cout << result << " ";
35 }
36 return 0;
37}
In this C++ solution, the program iterates over each subarray of length k, checks the order and consecutiveness of elements, and stores the maximum if the subarray meets the criteria.
This approach employs a sliding window technique to process each subarray of size k efficiently. We slide over the array and check whether each segment meets the criteria of being both sorted and consecutive. This reduces unnecessary re-checks by leveraging overlapping subarray properties.
Time Complexity: O(n * k)
, reduced by potentially not rechecking unchanged segments.
Space Complexity: O(n-k+1)
for the results array.
This C implementation uses a function to verify both order and consecutiveness of elements in a k-length sliding window. The maximum element is calculated if the conditions are met.