862. Shortest Subarray with Sum at Least K #843
-
Topics: Given an integer array A subarray is a contiguous part of an array. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to use a sliding window approach combined with prefix sums and a monotonic queue. Here's the step-by-step approach: Steps:
Algorithm:
Let's implement this solution in PHP: 862. Shortest Subarray with Sum at Least K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function shortestSubarray($nums, $k) {
$n = count($nums);
// Initialize prefix_sum array.
$prefix_sum = array_fill(0, $n + 1, 0);
// Compute the prefix sum array.
for ($i = 0; $i < $n; $i++) {
$prefix_sum[$i + 1] = $prefix_sum[$i] + $nums[$i];
}
// Monotonic queue to store indices of the prefix_sum array.
$deque = [];
$minLength = PHP_INT_MAX;
// Iterate over the prefix_sum array.
for ($i = 0; $i < $n + 1; $i++) {
// Remove elements from deque that do not form a valid subarray.
while (count($deque) > 0 && $prefix_sum[$i] - $prefix_sum[$deque[0]] >= $k) {
$minLength = min($minLength, $i - $deque[0]);
array_shift($deque); // Remove the front of the queue.
}
// Maintain the deque: remove all indices where prefix_sum[i] is less than the current value.
while (count($deque) > 0 && $prefix_sum[$i] <= $prefix_sum[$deque[count($deque) - 1]]) {
array_pop($deque); // Remove the back of the queue.
}
// Add current index to the deque.
array_push($deque, $i);
}
return $minLength == PHP_INT_MAX ? -1 : $minLength;
}
// Example usage:
$nums1 = [1];
$k1 = 1;
echo shortestSubarray($nums1, $k1) . "\n"; // Output: 1
$nums2 = [1, 2];
$k2 = 4;
echo shortestSubarray($nums2, $k2) . "\n"; // Output: -1
$nums3 = [2, -1, 2];
$k3 = 3;
echo shortestSubarray($nums3, $k3) . "\n"; // Output: 3
?> Explanation:
Time Complexity:
This approach ensures that the solution runs efficiently even for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to use a sliding window approach combined with prefix sums and a monotonic queue. Here's the step-by-step approach:
Steps:
Prefix Sum:
i
represents the sum of the elements from the start of the array toi
. The prefix sum allows us to compute the sum of any subarray in constant time.Monotonic Queue:
prefix_sum
array. The deque will be maintained in an increasing order of prefix sums.k
by comparing the current prefix sum with earlier prefix sums.Sliding Window …