Closed mah-shamim closed 4 hours ago
We can break down the task as follows:
nums
of length n
, and a positive integer k
. We need to consider all subarrays of size k
and compute their power.-1
otherwise.n - k + 1
, where each element corresponds to the power of the respective subarray.k
.-1
.nums[i+1] - nums[i] == 1
for every i
in the subarray.k
, check if it is sorted and return the maximum element if valid, otherwise return -1
.Let's implement this solution in PHP: 3254. Find the Power of K-Size Subarrays I
<?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer[]
*/
function resultsArray($nums, $k) {
$n = count($nums);
$result = [];
// Iterate through all subarrays of size k
for ($i = 0; $i <= $n - $k; $i++) {
$subarray = array_slice($nums, $i, $k);
$isSorted = true;
// Check if the subarray is sorted with consecutive elements
for ($j = 0; $j < $k - 1; $j++) {
if ($subarray[$j] + 1 !== $subarray[$j + 1]) {
$isSorted = false;
break;
}
}
// If sorted and consecutive, return the maximum, else -1
if ($isSorted) {
$result[] = max($subarray);
} else {
$result[] = -1;
}
}
return $result;
}
// Test cases
print_r(resultsArray([1, 2, 3, 4, 3, 2, 5], 3)); // Output: [3, 4, -1, -1, -1]
print_r(resultsArray([2, 2, 2, 2, 2], 4)); // Output: [-1, -1]
print_r(resultsArray([3, 2, 3, 2, 3, 2], 2)); // Output: [-1, 3, -1, 3, -1]
?>
for
loop from i = 0
to i = n - k
to consider all subarrays of size k
. For each subarray, we use array_slice()
to extract the subarray.1
.-1
.n - k + 1
subarrays.O(k)
time.O((n - k + 1) * k)
which simplifies to O(n * k)
.k = 1
, every subarray is trivially sorted (it only contains one element), and the power of each subarray will be the element itself.-1
.nums = [1, 2, 3, 4, 3, 2, 5], k = 3
, the output is [3, 4, -1, -1, -1]
.nums = [2, 2, 2, 2, 2], k = 4
, the output is [-1, -1]
.nums = [3, 2, 3, 2, 3, 2], k = 2
, the output is [-1, 3, -1, 3, -1]
.This solution should efficiently work for the problem constraints.
Discussed in https://github.com/mah-shamim/leet-code-in-php/discussions/839
1 <= nums[i] <= 105
- `1 <= k <= n` **Hint:** 1. Can we use a brute force solution with nested loops and HashSet? [^1]: **Subarray**: A subarray is a contiguous non-empty sequence of elements within an array.