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.
1import java.util.Arrays;
2
3public class SubarrayPower {
4
5 public static int[] findPowerOfSubarrays(int[] nums, int k) {
6 int n = nums.length;
7 int[] results = new int[n - k + 1];
8 Arrays.fill(results, -1);
9
10 for (int i = 0; i <= n - k; i++) {
11 boolean sortedAndConsecutive = true;
12 int maxElement = nums[i];
13 for (int j = 1; j < k; j++) {
14 if (nums[i + j] < nums[i + j - 1] || nums[i + j] != nums[i + j - 1] + 1) {
15 sortedAndConsecutive = false;
16 break;
17 }
18 if (nums[i + j] > maxElement) maxElement = nums[i + j];
19 }
20 if (sortedAndConsecutive)
21 results[i] = maxElement;
22 }
23 return results;
24 }
25
26 public static void main(String[] args) {
27 int[] nums = {1, 2, 3, 4, 3, 2, 5};
28 int k = 3;
29 int[] results = findPowerOfSubarrays(nums, k);
30 for (int result : results) {
31 System.out.print(result + " ");
32 }
33 }
34}
This Java implementation follows a similar pattern to ensure each segment of length k is verified and the power is determined.
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.
1public class SlidingWindow {
2
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 boolean 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(String[] args) {
20 int[] nums = {1, 2, 3, 4, 3, 2, 5};
21 int k = 3;
22 int[] results = findPowerWithSlidingWindow(nums, k);
23 for (int result : results) {
24 System.out.print(result + " ");
25 }
26 }
27}
This Java code aims to optimize power calculation by applying the sliding window technique to check each subarray's properties.