3254. Find the Power of K-Size Subarrays I #839
-
Topics: You are given an array of integers The power of an array is defined as:
You need to find the power of all subarrays1 of nums of size k. Return an integer array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can break down the task as follows: Problem Breakdown:
Plan:
Steps:
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]
?> Explanation:
Time Complexity:
Edge Case Considerations:
Example Outputs:
This solution should efficiently work for the problem constraints. |
Beta Was this translation helpful? Give feedback.
We can break down the task as follows:
Problem Breakdown:
nums
of lengthn
, and a positive integerk
. We need to consider all subarrays of sizek
and compute their power.-1
otherwise.n - k + 1
, where each element corresponds to the power of the respective subarray.Plan:
k
.