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.
For each subarray of size k, check if the elements are sorted in ascending order and are consecutive. If so, the power is the maximum element; otherwise, it’s -1. We can use a set to check for duplicates and compare min and max to verify consecutiveness.
classSolution {
fungetResults(nums: IntArray, k: Int): List<Int> {
val n = nums.size
val ans = mutableListOf<Int>()
for (i in0..n - k) {
var sorted = truevar mn = nums[i]
var mx = nums[i]
var prev = nums[i]
val st = mutableSetOf(nums[i])
for (j in i + 1 until i + k) {
if (nums[j] <= prev) sorted = false mn = minOf(mn, nums[j])
mx = maxOf(mx, nums[j])
st.add(nums[j])
prev = nums[j]
}
if (sorted && mx - mn == k - 1&& st.size == k)
ans.add(mx)
else ans.add(-1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defgetResults(self, nums: list[int], k: int) -> list[int]:
n = len(nums)
ans = []
for i in range(n - k +1):
window = nums[i:i+k]
if all(window[j] > window[j-1] for j in range(1, k)) and max(window) - min(window) == k -1and len(set(window)) == k:
ans.append(max(window))
else:
ans.append(-1)
return ans