Input: nums =[1,2,3,4,3,2,5], k =3Output: [3,4,-1,-1,-1]Explanation:
There are 5 subarrays of `nums` of size 3:-`[1, 2, 3]`with the maximum element 3.-`[2, 3, 4]`with the maximum element 4.-`[3, 4, 3]` whose elements are **not** consecutive.-`[4, 3, 2]` whose elements are **not** sorted.-`[3, 2, 5]` whose elements are **not** consecutive.
Example 2:
1
2
Input: nums =[2,2,2,2,2], k =4Output: [-1,-1]
Example 3:
1
2
Input: nums =[3,2,3,2,3,2], k =2Output: [-1,3,-1,3,-1]
Sliding window: We’ll use a sliding window of size k to examine each subarray from nums.
Check consecutiveness: For each subarray, check if the elements are consecutive and sorted in ascending order.
Determine power: If the subarray elements satisfy the consecutive and ascending condition, find the maximum value of that subarray; otherwise, return -1.
classSolution {
publicint[]resultsArray(int[] nums, int k) {
int n = nums.length;
int[] ans =newint[n - k + 1];
for (int i = 0; i <= n - k; i++) {
boolean isConsecutive =true;
for (int j = i + 1; j < i + k; j++) {
if (nums[j]!= nums[j - 1]+ 1) {
isConsecutive =false;
break;
}
}
if (isConsecutive) {
ans[i]= nums[i + k - 1];
} else {
ans[i]=-1;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defresults_array(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
ans = [0] * (n - k +1)
for i in range(n - k +1):
is_consecutive =Truefor j in range(i +1, i + k):
if nums[j] != nums[j -1] +1:
is_consecutive =Falsebreakif is_consecutive:
ans[i] = nums[i + k -1]
else:
ans[i] =-1return ans