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.
1using System;
2
3public class SubarrayPower {
4 public static int[] FindPowerOfSubarrays(int[] nums, int k) {
5 int n = nums.Length;
6 int[] results = new int[n - k + 1];
7 Array.Fill(results, -1);
8
9 for (int i = 0; i <= n - k; i++) {
10 bool sortedAndConsecutive = true;
11 int maxElement = nums[i];
12 for (int j = 1; j < k; j++) {
13 if (nums[i + j] < nums[i + j - 1] || nums[i + j] != nums[i + j - 1] + 1) {
14 sortedAndConsecutive = false;
15 break;
16 }
17 if (nums[i + j] > maxElement) {
18 maxElement = nums[i + j];
19 }
20 }
21 if (sortedAndConsecutive) {
22 results[i] = maxElement;
23 }
24 }
25 return results;
26 }
27
28 public static void Main() {
29 int[] nums = {1, 2, 3, 4, 3, 2, 5};
30 int k = 3;
31 int[] results = FindPowerOfSubarrays(nums, k);
32 Console.WriteLine(string.Join(" ", results));
33 }
34}
This C# solution analyzes each subarray of size k to confirm the ordering and consecutiveness, computing the power through iteration.
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.
1using System;
2public class SlidingWindow {
3 public static int[] FindPowerWithSlidingWindow(int[] nums, int k) {
4 int n = nums.Length;
5 int[] results = new int[n - k + 1];
6 for (int i = 0; i <= n - k; i++) {
7 bool isSortedAndConsecutive = true;
8 for (int j = 1; j < k; j++) {
9 if (nums[i + j] != nums[i + j - 1] + 1) {
10 isSortedAndConsecutive = false;
11 break;
12 }
13 }
14 results[i] = isSortedAndConsecutive ? nums[i + k - 1] : -1;
15 }
16 return results;
17 }
18
19 public static void Main() {
20 int[] nums = {1, 2, 3, 4, 3, 2, 5};
21 int k = 3;
22 int[] results = FindPowerWithSlidingWindow(nums, k);
23 Console.WriteLine(string.Join(" ", results));
24 }
25}
Employing sliding window optimization, this C# solution assesses each period and calculates power, limiting redundant processing.